const cloud = require("wx-server-sdk");
const xml2js = require('xml2js');
const crypto = require('crypto');
const https = require('https');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();

// 微信公众平台测试号配置
const WECHAT_CONFIG = {
  appId: 'wxdcdf0d04d9cdacd5',
  appSecret: '6ad94d415ba16a72470afe6f85676425'
};
// 微信支付配置（小微商户号 - 需要从商家助手小程序获取参数）
const WECHAT_PAY_CONFIG = {
  mchId: '1725988896', // 你的小微商户号
  appId: 'wxdcdf0d04d9cdacd5', // 微信小程序AppID
  apiKey: 'YOUR_API_KEY', // 需要从微信支付商家助手小程序获取
  notifyUrl: 'https://your-domain.com/api/pay/notify', // 支付结果通知地址
  sandbox: false // 使用正式环境
};



// 生成随机字符串
const generateNonceStr = (length = 32) => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return result;
};



// 生成签名
const generateSign = (params, apiKey) => {
  // 1. 参数排序
  const sortedKeys = Object.keys(params).sort();
  
  // 2. 拼接字符串
  let signString = '';
  sortedKeys.forEach(key => {
    if (params[key] !== '' && params[key] != null && key !== 'sign') {
      signString += `${key}=${params[key]}&`;
    }
  });
  signString += `key=${apiKey}`;
  
  // 3. MD5加密并转大写
  return crypto.createHash('md5').update(signString, 'utf8').digest('hex').toUpperCase();
};

// 生成XML
const generateXML = (params) => {
  const builder = new xml2js.Builder({
    rootName: 'xml',
    headless: true,
    renderOpts: { pretty: false }
  });
  return builder.buildObject(params);
};

// 解析XML
const parseXML = async (xmlString) => {
  const parser = new xml2js.Parser({
    explicitArray: false,
    ignoreAttrs: true
  });
  return await parser.parseStringPromise(xmlString);
};

// 获取openid
const getOpenId = async () => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  // 获取小程序二维码的buffer
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const { buffer } = resp;
  // 将图片上传云存储空间
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async () => {
  try {
    // 创建集合
    await db.createCollection("sales");
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "上海",
        sales: 11,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "南京",
        sales: 11,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "广州",
        sales: 22,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "深圳",
        sales: 22,
      },
    });
    return {
      success: true,
    };
  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    return {
      success: true,
      data: "create collection success",
    };
  }
};

// 查询数据
const selectRecord = async () => {
  // 返回数据库查询结果
  return await db.collection("sales").get();
};

// 更新数据
const updateRecord = async (event) => {
  try {
    // 遍历修改数据库信息
    for (let i = 0; i < event.data.length; i++) {
      await db
        .collection("sales")
        .where({
          _id: event.data[i]._id,
        })
        .update({
          data: {
            sales: event.data[i].sales,
          },
        });
    }
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 新增数据
const insertRecord = async (event) => {
  try {
    const insertRecord = event.data;
    // 插入数据
    await db.collection("sales").add({
      data: {
        region: insertRecord.region,
        city: insertRecord.city,
        sales: Number(insertRecord.sales),
      },
    });
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 删除数据
const deleteRecord = async (event) => {
  try {
    await db
      .collection("sales")
      .where({
        _id: event.data._id,
      })
      .remove();
    return {
      success: true,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 一键领取活动奖励
const claimActivityReward = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    console.log('一键领取活动奖励，openid:', openid);
    console.log('领取参数:', event);
    
    const { activityIds } = event; // 活动ID列表
    
    if (!activityIds || !Array.isArray(activityIds) || activityIds.length === 0) {
      return {
        success: false,
        errMsg: "请提供有效的活动ID列表"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const dailyActivities = gamesData.dailyActivities || [];
    const activities = gamesData.activities || [];
    const allActivities = [...dailyActivities, ...activities]; // 合并所有活动
    const goods = gamesData.goods || [];
    const users = gamesData.users || [];
    const backpacks = gamesData.backpacks || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const userId = currentUser._id;
    console.log('当前用户信息:', {
      userId: userId,
      points: currentUser.points,
      kills: currentUser.kills
    });
      
      const claimedActivities = []; // 成功领取的活动
      const failedActivities = []; // 领取失败的活动
      const addedItems = []; // 添加的物品记录
    
    // 处理每个活动
    for (const activityId of activityIds) {
      console.log(`开始处理活动: ${activityId}`);
      
      const activity = allActivities.find(a => (a._id === parseInt(activityId) || a._id === activityId) && !a.isDeleted);
      
      if (!activity) {
        failedActivities.push({
          activityId,
          reason: "活动不存在或已删除"
        });
        continue;
      }
      
      console.log('活动信息:', {
        id: activity._id,
        tag: activity.tag,
        goodsList: activity.goodsList,
        goodsSizeList: activity.goodsSizeList,
        claimedUsers: activity.claimedUsers
      });
      
      // 检查用户是否已领取过
      const claimedUsers = activity.claimedUsers || [];
      console.log(`活动 ${activityId} 的已领取用户列表:`, {
        claimedUsers: claimedUsers,
        claimedUsersTypes: claimedUsers.map(id => ({ id, type: typeof id })),
        currentUserId: userId,
        currentUserIdType: typeof userId,
        activityCreatedAt: activity.createdAt,
        activityTargetUsers: activity.targetUsers
      });
      
      // 检查是否是目标用户
      console.log(`检查目标用户匹配:`, {
        activityTargetUsers: activity.targetUsers,
        activityTargetUsersTypes: activity.targetUsers ? activity.targetUsers.map(id => ({ id, type: typeof id })) : [],
        currentUserId: userId,
        currentUserIdType: typeof userId
      });
      
      const isTargetUser = activity.targetUsers && activity.targetUsers.some(id => String(id) === String(userId));
      console.log(`用户 ${userId} 是否是活动 ${activityId} 的目标用户:`, isTargetUser);
      
      if (!isTargetUser) {
        failedActivities.push({
          activityId,
          reason: "不是此活动的目标用户"
        });
        continue;
      }
      
      const hasClaimed = claimedUsers.some(id => String(id) === String(userId));
      console.log(`用户 ${userId} 是否已领取活动 ${activityId}:`, hasClaimed);
      
      if (hasClaimed) {
        failedActivities.push({
          activityId,
          reason: "已领取过此活动奖励"
        });
        continue;
      }
      
      // 解析物品奖励
      const goodsIds = activity.goodsList ? activity.goodsList.split(',') : [];
      const goodsSizes = activity.goodsSizeList ? activity.goodsSizeList.split(',') : [];
      
      console.log(`活动 ${activityId} 的物品解析:`, {
        goodsList: activity.goodsList,
        goodsSizeList: activity.goodsSizeList,
        goodsIds: goodsIds,
        goodsSizes: goodsSizes
      });
      
      const activityItems = []; // 当前活动的物品
      
      // 处理每个物品
      for (let i = 0; i < goodsIds.length; i++) {
        const goodsId = goodsIds[i].trim();
        const size = goodsSizes[i] ? parseInt(goodsSizes[i].trim()) : 1;
        
        // 查找物品信息（支持字符串和数字ID匹配）
        const goodsItem = goods.find(g => (g._id === parseInt(goodsId) || g._id === goodsId) && !g.isDeleted);
        if (!goodsItem) {
          console.log(`物品不存在: goodsId=${goodsId}, 类型=${typeof goodsId}`);
          console.log('可用的物品ID:', (goods || []).map(g => ({ id: g._id, name: g.itemName, type: g.goodsType })));
          continue;
        }
        
        // 检查物品类型，如果是积分(4)或猎杀数(5)，直接添加到用户账户
        console.log(`处理物品: ${goodsItem.itemName}, goodsType: ${goodsItem.goodsType}, goodsId: ${goodsId}`);
        
        if (goodsItem.goodsType === 4 || goodsItem.goodsType === 5) {
          // 积分或猎杀数：直接添加到用户账户
          const userIndex = users.findIndex(u => u._id === userId);
          if (userIndex !== -1) {
            if (goodsItem.goodsType === 4) { // 积分
              users[userIndex].points += size;
              console.log(`直接添加积分: ${size}, 新积分: ${users[userIndex].points}`);
              
              // 记录积分增加行为
              await recordUserAction({
                actionType: 'points_add',
                actionDetail: '活动奖励积分',
                amount: size,
                itemName: goodsItem.itemName
              });
            } else if (goodsItem.goodsType === 5) { // 猎杀数
              users[userIndex].kills += size;
              console.log(`直接添加猎杀数: ${size}, 新猎杀数: ${users[userIndex].kills}`);
            }
            users[userIndex].updatedAt = new Date();
            console.log(`用户数据已更新: 积分=${users[userIndex].points}, 猎杀数=${users[userIndex].kills}`);
          } else {
            console.log('未找到用户，userId:', userId);
          }
        } else if (goodsItem.goodsType === 6) {
          // 背包积分：添加到背包，不直接加入个人账户
          const existingBackpackItem = backpacks.find(b => 
            String(b.userId) === String(userId) && 
            (b.goodsId === parseInt(goodsId) || b.goodsId === goodsId) && 
            !b.isDeleted
          );
          
          if (existingBackpackItem) {
            // 更新数量
            existingBackpackItem.quantity += size;
            existingBackpackItem.updatedAt = new Date();
            console.log(`更新背包积分数量: ${goodsItem.itemName}, 新数量: ${existingBackpackItem.quantity}`);
          } else {
            // 新增背包积分到背包
            const newBackpackItem = {
              _id: Date.now() + Math.floor(Math.random() * 1000),
              userId: userId,
              goodsId: goodsId,
              quantity: size,
              source: "活动奖励",
              sourceId: activityId,
              storedAt: new Date(),
              usedAt: null,
              isDeleted: false
            };
            backpacks.push(newBackpackItem);
            console.log(`新增背包积分到背包: ${goodsItem.itemName}, 数量: ${size}`);
          }
          console.log(`背包积分已存入背包，需要用户手动使用才能加入个人账户`);
        } else {
          // 普通活动：添加到背包
          // 查找用户背包中是否已有此物品
          const existingBackpackItem = backpacks.find(b => 
            String(b.userId) === String(userId) && 
            (b.goodsId === parseInt(goodsId) || b.goodsId === goodsId) && 
            !b.isDeleted
          );
          
          if (existingBackpackItem) {
            // 更新数量
            existingBackpackItem.quantity += size;
            existingBackpackItem.updatedAt = new Date();
            console.log(`更新物品数量: ${goodsItem.itemName}, 新数量: ${existingBackpackItem.quantity}`);
          } else {
            // 新增物品到背包
            const newBackpackItem = {
              _id: Date.now() + Math.floor(Math.random() * 1000),
              userId: userId,
              goodsId: goodsId,
              quantity: size,
              source: "活动奖励",
              sourceId: activityId,
              storedAt: new Date(),
              usedAt: null,
              isDeleted: false
            };
            backpacks.push(newBackpackItem);
            console.log(`新增物品到背包: ${goodsItem.itemName}, 数量: ${size}`);
          }
        }
        
        activityItems.push({
          goodsId: goodsId,
          itemName: goodsItem.itemName,
          quantity: size
        });
      }
      
      // 记录用户领取信息
      claimedUsers.push(userId);
      
      // 更新活动数据
      const activityIndex = activities.findIndex(a => a._id === activityId);
      if (activityIndex !== -1) {
        activities[activityIndex].claimedUsers = claimedUsers;
      }
      
      claimedActivities.push({
        activityId: activityId,
        activityName: activity.tag,
        items: activityItems
      });
      
      addedItems.push(...activityItems);
    }
    
    // 更新数据库
    const updateData = {
      dailyActivities: dailyActivities,
      activities: activities
    };
    
    // 如果有背包更新，添加到更新数据中
    if (backpacks.length > 0) {
      updateData.backpacks = backpacks;
      console.log('背包数据已更新，数量:', backpacks.length);
      
      // 调试：显示背包中的背包积分
      const backpackPoints = (backpacks || []).find(b => {
        const goodsInfo = (goods || []).find(g => (g._id === parseInt(b.goodsId) || g._id === b.goodsId) && !g.isDeleted);
        return goodsInfo && goodsInfo.goodsType === 6 && String(b.userId) === String(userId);
      });
      
      if (backpackPoints) {
        console.log('背包积分信息:', {
          userId: backpackPoints.userId,
          goodsId: backpackPoints.goodsId,
          quantity: backpackPoints.quantity,
          storedAt: backpackPoints.storedAt
        });
      }
    }
    
    // 如果有用户数据更新，添加到更新数据中
    if (users.length > 0) {
      updateData.users = users;
      console.log('用户数据已更新，数量:', users.length);
      
      // 显示当前用户的积分和猎杀数
      const currentUser = users.find(u => u._id === userId);
      if (currentUser) {
        console.log('当前用户数据:', {
          userId: currentUser._id,
          points: currentUser.points,
          kills: currentUser.kills,
          updatedAt: currentUser.updatedAt
        });
      }
    }
    
    console.log('准备更新数据库，updateData:', Object.keys(updateData));
    console.log('背包数据详情:', (backpacks || []).map(b => ({
      userId: b.userId,
      goodsId: b.goodsId,
      quantity: b.quantity,
      isDeleted: b.isDeleted
    })));
    
    await db.collection("games").doc(gamesData._id).update({
      data: updateData
    });
    
    console.log('数据库更新完成');
    
    console.log('领取结果:', {
      claimedActivities,
      failedActivities,
      addedItems
    });
    
    return {
      success: true,
      data: {
        claimedActivities: claimedActivities,
        failedActivities: failedActivities,
        addedItems: addedItems,
        totalClaimed: claimedActivities.length,
        totalFailed: failedActivities.length
      },
      message: `成功领取 ${claimedActivities.length} 个活动，失败 ${failedActivities.length} 个`
    };
    
  } catch (error) {
    console.error('一键领取活动奖励错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取积分商城列表
const getPointsShopList = async (event) => {
  try {
    console.log('获取积分商城列表');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 查询games集合中的商城信息
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const pointsShop = gamesData.pointsShop || [];
      const goods = gamesData.goods || [];
      const users = gamesData.users || [];
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      const userShopId = currentUser ? currentUser.shopId : null;
      
      console.log('商城商品数量:', pointsShop.length);
      console.log('物品数量:', goods.length);
      console.log('用户店铺ID:', userShopId);
      
      // 处理商城列表，关联物品信息
      let shopList = pointsShop
        .filter(item => !item.isDeleted)
        .map(shopItem => {
          // 查找对应的物品信息
          const goodsItem = goods.find(g => g._id === shopItem.goodsId && !g.isDeleted);
          // 查找对应的店铺信息
          const shop = shops.find(s => s._id === shopItem.shopId && !s.isDeleted);
          
          if (goodsItem) {
            return {
              _id: shopItem._id,
              goodsId: shopItem.goodsId,
              shopId: shopItem.shopId,
              shopName: shop ? shop.name : '未知店铺',
              itemName: goodsItem.itemName,
              itemImage: goodsItem.itemImage,
              goodsType: goodsItem.goodsType,
              oldPrice: shopItem.oldPrice || 0,
              price: shopItem.price || 0,
              createdAt: shopItem.createdAt
            };
          }
          return null;
        })
        .filter(item => item !== null); // 过滤掉没有对应物品的商品
      
      // 如果用户已登录，只显示用户绑定店铺的商品
      if (userShopId) {
        shopList = shopList.filter(item => item.shopId === userShopId);
      }
      
      console.log('处理后的商城列表:', shopList);
      
      return {
        success: true,
        data: shopList,
        total: shopList.length
      };
    } else {
      console.log('games集合不存在');
      return {
        success: true,
        data: [],
        total: 0
      };
    }
  } catch (error) {
    console.error('获取积分商城列表错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：添加积分商城商品
const addPointsShopItem = async (event) => {
  try {
    console.log('添加积分商城商品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { itemName, oldPrice, price, shopId } = event; // 超级管理员可以指定shopId
    
    if (!itemName || !oldPrice || !price) {
      return {
        success: false,
        errMsg: "商品名称、原价和现价不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const goods = gamesData.goods || [];
      const pointsShop = gamesData.pointsShop || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以添加商品"
        };
      }
      
      // 查找物品表中是否有相同名称的物品
      let goodsItem = goods.find(g => g.itemName === itemName && !g.isDeleted);
      
      if (!goodsItem) {
        // 如果没有找到相同名称的物品，创建一个新的物品
        const newGoodsId = Date.now() + Math.floor(Math.random() * 1000);
        goodsItem = {
          _id: newGoodsId,
          itemName: itemName,
          itemImage: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0", // 默认图片
          goodsType: 0, // 默认普通物品
          storedAt: new Date(),
          usedAt: null,
          isDeleted: false
        };
        
        // 添加新物品到goods数组
        gamesData.goods.push(goodsItem);
      }
      
      // 确定目标店铺ID
      let targetShopId;
      if (currentUser.permission === 1) {
        // 超级管理员可以指定店铺ID
        targetShopId = shopId ? parseInt(shopId) : currentUser.shopId;
      } else {
        // 管理员只能添加自己店铺的商品
        targetShopId = currentUser.shopId;
      }
      
      // 创建新的积分商城商品
      const newShopItem = {
        _id: Date.now() + Math.floor(Math.random() * 1000),
        goodsId: goodsItem._id,
        shopId: targetShopId,
        oldPrice: parseInt(oldPrice),
        price: parseInt(price),
        createdAt: new Date(),
        isDeleted: false
      };
      
      // 添加新商品到积分商城
      gamesData.pointsShop.push(newShopItem);
      
      // 更新数据库
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: {
          goods: gamesData.goods,
          pointsShop: gamesData.pointsShop
        }
      });
      
      return {
        success: true,
        data: {
          shopItem: newShopItem,
          goodsItem: goodsItem
        },
        message: "商品添加成功"
      };
    } else {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
  } catch (error) {
    console.error('添加积分商城商品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：更新积分商城商品
const updatePointsShopItem = async (event) => {
  try {
    console.log('更新积分商城商品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopItemId, oldPrice, price, shopId } = event; // 超级管理员可以指定shopId
    
    if (!shopItemId || !oldPrice || !price) {
      return {
        success: false,
        errMsg: "商品ID、原价和现价不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const pointsShop = gamesData.pointsShop || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以更新商品"
        };
      }
      
      // 查找要更新的商品
      const shopItemIndex = pointsShop.findIndex(item => item._id === parseInt(shopItemId) && !item.isDeleted);
      
      if (shopItemIndex === -1) {
        return {
          success: false,
          errMsg: "商品不存在"
        };
      }
      
      const shopItem = pointsShop[shopItemIndex];
      
      // 检查权限：管理员只能更新自己店铺的商品，超级管理员可以更新任何商品
      if (currentUser.permission === 2 && shopItem.shopId !== currentUser.shopId) {
        return {
          success: false,
          errMsg: "权限不足，只能更新自己店铺的商品"
        };
      }
      
      // 超级管理员可以指定不同的店铺ID来更新商品
      if (currentUser.permission === 1 && shopId && shopId !== shopItem.shopId) {
        // 超级管理员想要将商品转移到其他店铺
        shopItem.shopId = shopId;
      }
      
      // 更新商品信息
      pointsShop[shopItemIndex] = {
        ...shopItem,
        oldPrice: parseInt(oldPrice),
        price: parseInt(price)
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: {
          pointsShop: pointsShop
        }
      });
      
      return {
        success: true,
        data: pointsShop[shopItemIndex],
        message: "商品更新成功"
      };
    } else {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
  } catch (error) {
    console.error('更新积分商城商品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：删除积分商城商品
const deletePointsShopItem = async (event) => {
  try {
    console.log('删除积分商城商品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopItemId, shopId } = event; // 超级管理员可以指定shopId
    
    if (!shopItemId) {
      return {
        success: false,
        errMsg: "商品ID不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const pointsShop = gamesData.pointsShop || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以删除商品"
        };
      }
      
      // 查找要删除的商品
      let shopItemIndex;
      if (currentUser.permission === 1 && shopId) {
        // 超级管理员指定了店铺ID，在该店铺中查找商品
        shopItemIndex = pointsShop.findIndex(item => 
          item._id === parseInt(shopItemId) && 
          !item.isDeleted && 
          item.shopId === shopId
        );
      } else {
        // 普通查找
        shopItemIndex = pointsShop.findIndex(item => item._id === parseInt(shopItemId) && !item.isDeleted);
      }
      
      if (shopItemIndex === -1) {
        return {
          success: false,
          errMsg: "商品不存在"
        };
      }
      
      const shopItem = pointsShop[shopItemIndex];
      
      // 检查权限：管理员只能删除自己店铺的商品，超级管理员可以删除任何商品
      if (currentUser.permission === 2 && shopItem.shopId !== currentUser.shopId) {
        return {
          success: false,
          errMsg: "权限不足，只能删除自己店铺的商品"
        };
      }
      
      // 逻辑删除商品
      pointsShop[shopItemIndex] = {
        ...shopItem,
        isDeleted: true
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: {
          pointsShop: pointsShop
        }
      });
      
      return {
        success: true,
        message: "商品删除成功"
      };
    } else {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
  } catch (error) {
    console.error('删除积分商城商品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：获取积分商城商品列表（管理用）
const getPointsShopItemsForAdmin = async (event) => {
  try {
    console.log('获取积分商城商品列表（管理用）');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopId } = event; // 超级管理员可以指定店铺ID
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const goods = gamesData.goods || [];
      const pointsShop = gamesData.pointsShop || [];
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以查看商品列表"
        };
      }
      
      // 确定要查询的店铺ID
      let targetShopId;
      if (currentUser.permission === 1) {
        // 超级管理员可以指定店铺ID
        targetShopId = shopId ? parseInt(shopId) : currentUser.shopId;
      } else {
        // 管理员只能查看自己店铺的商品
        targetShopId = currentUser.shopId;
      }
      
      console.log('积分商城管理 - 目标店铺ID:', targetShopId, '类型:', typeof targetShopId);
      
      // 处理商城列表，关联物品信息
      let shopList = pointsShop
        .filter(item => {
          const match = !item.isDeleted && item.shopId === targetShopId;
          if (item.shopId === targetShopId) {
            console.log('匹配的商品:', item._id, '店铺ID:', item.shopId, '类型:', typeof item.shopId);
          }
          return match;
        })
        .map(shopItem => {
          // 查找对应的物品信息
          const goodsItem = goods.find(g => g._id === shopItem.goodsId && !g.isDeleted);
          // 查找对应的店铺信息
          const shop = shops.find(s => s._id === shopItem.shopId && !s.isDeleted);
          
          if (goodsItem) {
            return {
              _id: shopItem._id,
              goodsId: shopItem.goodsId,
              shopId: shopItem.shopId,
              shopName: shop ? shop.name : '未知店铺',
              itemName: goodsItem.itemName,
              itemImage: goodsItem.itemImage,
              goodsType: goodsItem.goodsType,
              oldPrice: shopItem.oldPrice || 0,
              price: shopItem.price || 0,
              createdAt: shopItem.createdAt
            };
          }
          return null;
        })
        .filter(item => item !== null); // 过滤掉没有对应物品的商品
      
      console.log('管理用商城列表:', shopList);
      
      return {
        success: true,
        data: shopList,
        total: shopList.length
      };
    } else {
      console.log('games集合不存在');
      return {
        success: true,
        data: [],
        total: 0
      };
    }
  } catch (error) {
    console.error('获取积分商城商品列表错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 购买饮品
const purchaseDrink = async (event) => {
  try {
    console.log('购买饮品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 获取前端传递的参数
    const { drinkId, paymentType } = event; // paymentType: 'points' 或 'coupon'
    
    console.log('购买参数:', { drinkId, paymentType });
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const drinks = gamesData.drinks || [];
    const backpacks = gamesData.backpacks || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    // 查找饮品信息（支持字符串和数字ID）
    const drinkItem = drinks.find(d => (d._id === parseInt(drinkId) || d._id === drinkId) && !d.isDeleted);
    if (!drinkItem) {
      return {
        success: false,
        errMsg: "饮品不存在"
      };
    }
    
    // 检查用户是否有权限购买该店铺的饮品
    // 普通用户只能购买自己店铺的饮品，管理员和超级管理员可以购买任何店铺的饮品
    if (currentUser.permission === 3 && currentUser.shopId !== drinkItem.shopId) {
      return {
        success: false,
        errMsg: "您只能购买自己店铺的饮品"
      };
    }
    
    console.log('饮品信息:', drinkItem);
    console.log('用户信息:', currentUser);
    
    // 根据支付方式处理购买逻辑
    if (paymentType === 'points') {
      // 使用积分购买
      if (currentUser.points < drinkItem.price) {
        return {
          success: false,
          errMsg: `积分不足，需要${drinkItem.price}积分，当前只有${currentUser.points}积分`
        };
      }
      
      // 扣除积分
      const userIndex = users.findIndex(u => u._id === currentUser._id);
      users[userIndex].points -= drinkItem.price;
      users[userIndex].updatedAt = new Date();
      
      console.log(`扣除积分: ${drinkItem.price}, 剩余积分: ${users[userIndex].points}`);
      
      // 记录积分减少行为
      await recordUserAction({
        actionType: 'points_subtract',
        actionDetail: '购买饮品',
        amount: drinkItem.price,
        itemName: drinkItem.name
      });
      
    } else if (paymentType === 'coupon') {
      // 使用饮品券购买
      // 查找用户的饮品券
      const drinkCoupon = backpacks.find(b => 
        b.userId === currentUser._id && 
        b.goodsId === 1003 && // 可乐券的ID
        !b.isDeleted && 
        b.quantity > 0
      );
      
      if (!drinkCoupon) {
        return {
          success: false,
          errMsg: "没有饮品券，请先获取饮品券"
        };
      }
      
      // 扣除一张饮品券
      const backpackIndex = backpacks.findIndex(b => b._id === drinkCoupon._id);
      backpacks[backpackIndex].quantity -= 1;
      
      // 如果饮品券数量为0，标记为删除
      if (backpacks[backpackIndex].quantity === 0) {
        backpacks[backpackIndex].isDeleted = true;
      }
      
      console.log(`扣除饮品券: 1张, 剩余数量: ${backpacks[backpackIndex].quantity}`);
      
    } else {
      return {
        success: false,
        errMsg: "无效的支付方式"
      };
    }
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        backpacks: backpacks
      }
    });
    
    console.log('购买成功');
    
    return {
      success: true,
      data: {
        message: "购买成功",
        drinkName: drinkItem.name,
        paymentType: paymentType,
        cost: paymentType === 'points' ? `${drinkItem.price}积分` : '1张饮品券',
        remainingPoints: paymentType === 'points' ? users.find(u => u._id === currentUser._id).points : currentUser.points,
        remainingCoupons: paymentType === 'coupon' ? 
          (backpacks.find(b => b.userId === currentUser._id && b.goodsId === 1003 && !b.isDeleted)?.quantity || 0) : 
          (backpacks.find(b => b.userId === currentUser._id && b.goodsId === 1003 && !b.isDeleted)?.quantity || 0)
      }
    };
    
  } catch (error) {
    console.error('购买饮品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取饮品列表
const getDrinksList = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    console.log('获取饮品列表，openid:', openid);
    
    // 查询games集合中的饮品信息
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const drinks = gamesData.drinks || [];
      const users = gamesData.users || [];
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      const userShopId = currentUser ? currentUser.shopId : null;
      
      console.log('饮品数量:', drinks.length);
      console.log('用户店铺ID:', userShopId);
      
      // 过滤未删除的饮品，并根据用户店铺筛选
      let drinksList = drinks.filter(drink => !drink.isDeleted);
      
      // 如果用户已登录，只显示用户绑定店铺的饮品
      if (userShopId) {
        drinksList = drinksList.filter(drink => drink.shopId === userShopId);
      }
      
      // 添加店铺信息
      drinksList = drinksList.map(drink => {
        const shopInfo = shops.find(s => s._id === drink.shopId && !s.isDeleted);
        return {
          ...drink,
          shopName: shopInfo ? shopInfo.name : '未知店铺'
        };
      });
      
      console.log('处理后的饮品列表:', drinksList);
      
      return {
        success: true,
        data: drinksList,
        total: drinksList.length
      };
    } else {
      console.log('games集合不存在');
      return {
        success: true,
        data: [],
        total: 0
      };
    }
  } catch (error) {
    console.error('获取饮品列表错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：添加饮品
const addDrink = async (event) => {
  try {
    console.log('添加饮品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { name, imageUrl, price, description, shopId } = event; // 超级管理员可以指定shopId
    
    if (!name || !price) {
      return {
        success: false,
        errMsg: "饮品名称和价格不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const drinks = gamesData.drinks || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以添加饮品"
        };
      }
      
      // 确定目标店铺ID
      let targetShopId;
      if (currentUser.permission === 1) {
        // 超级管理员可以指定店铺ID
        targetShopId = shopId ? parseInt(shopId) : currentUser.shopId;
      } else {
        // 管理员只能添加自己店铺的饮品
        targetShopId = currentUser.shopId;
      }
      
      // 创建新的饮品
      const newDrink = {
        _id: Date.now() + Math.floor(Math.random() * 1000),
        shopId: targetShopId,
        name: name,
        imageUrl: imageUrl || "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0", // 默认图片
        price: parseInt(price),
        description: description || "",
        createdAt: new Date(),
        isDeleted: false
      };
      
      // 添加新饮品到饮品列表
      gamesData.drinks.push(newDrink);
      
      // 更新数据库
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: {
          drinks: gamesData.drinks
        }
      });
      
      return {
        success: true,
        data: newDrink,
        message: "饮品添加成功"
      };
    } else {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
  } catch (error) {
    console.error('添加饮品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：更新饮品
const updateDrink = async (event) => {
  try {
    console.log('更新饮品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { drinkId, name, imageUrl, price, description, shopId } = event; // 超级管理员可以指定shopId
    
    if (!drinkId || !name || !price) {
      return {
        success: false,
        errMsg: "饮品ID、名称和价格不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const drinks = gamesData.drinks || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以更新饮品"
        };
      }
      
      // 查找要更新的饮品
      let drinkIndex;
      if (currentUser.permission === 1 && shopId) {
        // 超级管理员指定了店铺ID，在该店铺中查找饮品
        drinkIndex = drinks.findIndex(drink => 
          drink._id === parseInt(drinkId) && 
          !drink.isDeleted && 
          drink.shopId === shopId
        );
      } else {
        // 普通查找
        drinkIndex = drinks.findIndex(drink => drink._id === parseInt(drinkId) && !drink.isDeleted);
      }
      
      if (drinkIndex === -1) {
        return {
          success: false,
          errMsg: "饮品不存在"
        };
      }
      
      const drink = drinks[drinkIndex];
      
      // 检查权限：管理员只能更新自己店铺的饮品，超级管理员可以更新任何饮品
      if (currentUser.permission === 2 && drink.shopId !== currentUser.shopId) {
        return {
          success: false,
          errMsg: "权限不足，只能更新自己店铺的饮品"
        };
      }
      
      // 超级管理员可以指定不同的店铺ID来更新饮品
      if (currentUser.permission === 1 && shopId && shopId !== drink.shopId) {
        // 超级管理员想要将饮品转移到其他店铺
        drink.shopId = shopId;
      }
      
      // 更新饮品信息
      drinks[drinkIndex] = {
        ...drink,
        name: name,
        imageUrl: imageUrl || drink.imageUrl,
        price: parseInt(price),
        description: description || drink.description
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: {
          drinks: drinks
        }
      });
      
      return {
        success: true,
        data: drinks[drinkIndex],
        message: "饮品更新成功"
      };
    } else {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
  } catch (error) {
    console.error('更新饮品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：删除饮品
const deleteDrink = async (event) => {
  try {
    console.log('删除饮品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { drinkId, shopId } = event; // 超级管理员可以指定shopId
    
    if (!drinkId) {
      return {
        success: false,
        errMsg: "饮品ID不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const drinks = gamesData.drinks || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以删除饮品"
        };
      }
      
      // 查找要删除的饮品
      let drinkIndex;
      if (currentUser.permission === 1 && shopId) {
        // 超级管理员指定了店铺ID，在该店铺中查找饮品
        drinkIndex = drinks.findIndex(drink => 
          drink._id === parseInt(drinkId) && 
          !drink.isDeleted && 
          drink.shopId === shopId
        );
      } else {
        // 普通查找
        drinkIndex = drinks.findIndex(drink => drink._id === parseInt(drinkId) && !drink.isDeleted);
      }
      
      if (drinkIndex === -1) {
        return {
          success: false,
          errMsg: "饮品不存在"
        };
      }
      
      const drink = drinks[drinkIndex];
      
      // 检查权限：管理员只能删除自己店铺的饮品，超级管理员可以删除任何饮品
      if (currentUser.permission === 2 && drink.shopId !== currentUser.shopId) {
        return {
          success: false,
          errMsg: "权限不足，只能删除自己店铺的饮品"
        };
      }
      
      // 逻辑删除饮品
      drinks[drinkIndex] = {
        ...drink,
        isDeleted: true
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: {
          drinks: drinks
        }
      });
      
      return {
        success: true,
        message: "饮品删除成功"
      };
    } else {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
  } catch (error) {
    console.error('删除饮品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 管理员：获取饮品列表（管理用）
const getDrinksForAdmin = async (event) => {
  try {
    console.log('获取饮品列表（管理用）');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopId } = event; // 超级管理员可以指定店铺ID
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const drinks = gamesData.drinks || [];
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：管理员或超级管理员
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以查看饮品列表"
        };
      }
      
      // 确定要查询的店铺ID
      let targetShopId;
      if (currentUser.permission === 1) {
        // 超级管理员可以指定店铺ID
        targetShopId = shopId ? parseInt(shopId) : currentUser.shopId;
      } else {
        // 管理员只能查看自己店铺的饮品
        targetShopId = currentUser.shopId;
      }
      
      console.log('饮品管理 - 目标店铺ID:', targetShopId, '类型:', typeof targetShopId);
      
      // 过滤未删除的饮品，并根据店铺筛选
      let drinksList = drinks.filter(drink => {
        const match = !drink.isDeleted && drink.shopId === targetShopId;
        if (drink.shopId === targetShopId) {
          console.log('匹配的饮品:', drink.name, '店铺ID:', drink.shopId, '类型:', typeof drink.shopId);
        }
        return match;
      });
      
      // 添加店铺信息
      drinksList = drinksList.map(drink => {
        const shopInfo = shops.find(s => s._id === drink.shopId && !s.isDeleted);
        return {
          ...drink,
          shopName: shopInfo ? shopInfo.name : '未知店铺'
        };
      });
      
      console.log('管理用饮品列表:', drinksList);
      
      return {
        success: true,
        data: drinksList,
        total: drinksList.length
      };
    } else {
      console.log('games集合不存在');
      return {
        success: true,
        data: [],
        total: 0
      };
    }
  } catch (error) {
    console.error('获取饮品列表错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 清空games数据库
const clearGamesDatabase = async (event) => {
  try {
    console.log('清空games数据库');
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      // 删除所有games文档
      for (const doc of gamesResult.data) {
        await db.collection("games").doc(doc._id).remove();
      }
      
      console.log('games数据库已清空');
      
      return {
        success: true,
        message: "games数据库已成功清空"
      };
    } else {
      return {
        success: true,
        message: "games数据库已经是空的"
      };
    }
    
  } catch (error) {
    console.error('清空games数据库错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 购买商城商品
const purchaseShopItem = async (event) => {
  try {
    console.log('购买商城商品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopItemId } = event; // 商城商品ID
    
    if (!shopItemId) {
      return {
        success: false,
        errMsg: "请提供有效的商品ID"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const pointsShop = gamesData.pointsShop || [];
    const goods = gamesData.goods || [];
    const users = gamesData.users || [];
    const backpacks = gamesData.backpacks || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const userId = currentUser._id;
    
    // 查找要购买的商品
    const shopItem = pointsShop.find(item => item._id === shopItemId && !item.isDeleted);
    if (!shopItem) {
      return {
        success: false,
        errMsg: "商品不存在或已下架"
      };
    }
    
    // 查找对应的物品信息
    const goodsItem = goods.find(g => g._id === shopItem.goodsId && !g.isDeleted);
    if (!goodsItem) {
      return {
        success: false,
        errMsg: "物品信息不存在"
      };
    }
    
    // 检查用户积分是否足够
    if (currentUser.points < shopItem.price) {
      return {
        success: false,
        errMsg: `积分不足，需要${shopItem.price}积分，当前只有${currentUser.points}积分`
      };
    }
    
    // 扣除用户积分
    const userIndex = users.findIndex(u => u._id === userId);
    if (userIndex !== -1) {
      users[userIndex].points -= shopItem.price;
      users[userIndex].updatedAt = new Date();
      
      // 记录积分减少行为
      await recordUserAction({
        actionType: 'points_subtract',
        actionDetail: '商城购买',
        amount: shopItem.price,
        itemName: goodsItem.itemName
      });
    }
    
    // 查找用户背包中是否已有此物品
    const existingBackpackItem = backpacks.find(b => 
      b.userId === userId && 
      b.goodsId === shopItem.goodsId && 
      !b.isDeleted
    );
    
    if (existingBackpackItem) {
      // 更新数量
      existingBackpackItem.quantity += 1;
      existingBackpackItem.updatedAt = new Date();
      console.log(`更新物品数量: ${goodsItem.itemName}, 新数量: ${existingBackpackItem.quantity}`);
    } else {
      // 新增物品到背包
      const newBackpackItem = {
        _id: Date.now() + Math.floor(Math.random() * 1000),
        userId: userId,
        goodsId: shopItem.goodsId,
        quantity: 1,
        source: "商城购买",
        sourceId: shopItemId,
        storedAt: new Date(),
        usedAt: null,
        isDeleted: false
      };
      backpacks.push(newBackpackItem);
      console.log(`新增物品到背包: ${goodsItem.itemName}`);
    }
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        backpacks: backpacks
      }
    });
    
    console.log('购买成功');
    
    return {
      success: true,
      data: {
        message: "购买成功",
        itemName: goodsItem.itemName,
        price: shopItem.price,
        remainingPoints: users[userIndex].points
      }
    };
    
  } catch (error) {
    console.error('购买商品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户背包物品
const getUserBackpack = async (event) => {
  try {
    console.log('获取用户背包物品');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 获取前端传递的物品类别ID（可选参数）
    const { goodsType } = event;
    console.log('请求的物品类别ID:', goodsType);
    
    // 查询games集合中的背包信息
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const backpacks = gamesData.backpacks || [];
      const goods = gamesData.goods || [];
      const users = gamesData.users || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      const userId = currentUser ? currentUser._id : null;
      
      console.log('背包物品数量:', backpacks.length);
      console.log('物品数量:', goods.length);
      console.log('当前用户ID:', userId);
      
      if (!userId) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 处理背包物品，关联物品信息
      console.log('原始背包物品:', backpacks.filter(item => String(item.userId) === String(userId)));
      console.log('充值兑换券物品:', backpacks.filter(item => String(item.userId) === String(userId) && (item.goodsId === parseInt(1006) || item.goodsId === 1006)));
      console.log('背包积分物品:', backpacks.filter(item => String(item.userId) === String(userId) && (item.goodsId === parseInt(1009) || item.goodsId === 1009)));
      
      let backpackList = backpacks
        .filter(item => String(item.userId) === String(userId) && !item.isDeleted && item.quantity > 0)
        .map(backpackItem => {
          // 查找对应的物品信息（支持字符串和数字ID匹配）
          const goodsItem = goods.find(g => (g._id === parseInt(backpackItem.goodsId) || g._id === backpackItem.goodsId) && !g.isDeleted);
          
          if (goodsItem) {
            return {
              _id: backpackItem._id,
              goodsId: backpackItem.goodsId,
              itemName: goodsItem.itemName,
              itemImage: goodsItem.itemImage,
              goodsType: goodsItem.goodsType,
              quantity: backpackItem.quantity,
              source: backpackItem.source,
              sourceId: backpackItem.sourceId,
              storedAt: backpackItem.storedAt,
              usedAt: backpackItem.usedAt
            };
          } else {
            console.log('未找到对应的物品信息，goodsId:', backpackItem.goodsId);
          }
          return null;
        })
        .filter(item => item !== null); // 过滤掉没有对应物品的背包项
      
      // 如果指定了物品类别ID，则进行筛选
      if (goodsType !== undefined && goodsType !== null) {
        backpackList = backpackList.filter(item => item.goodsType === parseInt(goodsType));
        console.log(`按物品类别ID ${goodsType} 筛选后的背包列表:`, backpackList);
      }
      
      console.log('处理后的背包列表:', backpackList);
      
      return {
        success: true,
        data: backpackList,
        total: backpackList.length,
        currentUserId: userId
      };
    } else {
      console.log('games集合不存在');
      return {
        success: true,
        data: [],
        total: 0,
        currentUserId: null
      };
    }
  } catch (error) {
    console.error('获取用户背包物品错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取活动列表
const getActivityList = async (event) => {
  try {
    console.log('获取活动列表');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 查询games集合中的活动信息
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const activities = gamesData.activities || []; // 普通活动
      const dailyActivities = gamesData.dailyActivities || []; // 每日活动
      const goods = gamesData.goods || [];
      const users = gamesData.users || [];
      const userActivityStates = gamesData.userActivityStates || []; // 新增用户活动状态
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      const userId = currentUser ? currentUser._id : null;
      const userShopId = currentUser ? currentUser.shopId : null; // 获取用户绑定的店铺ID
      
      console.log('普通活动数量:', activities.length);
      console.log('每日活动数量:', dailyActivities.length);
      console.log('物品数量:', goods.length);
      console.log('当前用户ID:', userId, '类型:', typeof userId);
      console.log('用户店铺ID:', userShopId, '类型:', typeof userShopId);
      console.log('用户活动状态数量:', userActivityStates.length);
      console.log('普通活动列表:', activities.map(a => ({ 
        id: a._id, 
        title: a.title,
        tag: a.tag, 
        shopId: a.shopId,
        shopIdType: typeof a.shopId,
        targetUsers: a.targetUsers,
        targetUsersType: a.targetUsers ? a.targetUsers.map(id => ({ id, type: typeof id })) : [],
        goodsList: a.goodsList, 
        claimedUsers: a.claimedUsers 
      })));
      console.log('每日活动列表:', dailyActivities.map(a => ({ 
        id: a._id, 
        title: a.title,
        tag: a.tag, 
        shopId: a.shopId,
        shopIdType: typeof a.shopId,
        targetUsers: a.targetUsers,
        targetUsersType: a.targetUsers ? a.targetUsers.map(id => ({ id, type: typeof id })) : [],
        goodsList: a.goodsList, 
        claimedUsers: a.claimedUsers 
      })));
       
       // 合并普通活动和每日活动，并去重
       const allActivities = [...activities, ...dailyActivities];
       
       // 去重：根据活动ID去重，保留第一个出现的活动
       const uniqueActivities = [];
       const seenIds = new Set();
       for (const activity of allActivities) {
         if (!seenIds.has(activity._id)) {
           seenIds.add(activity._id);
           uniqueActivities.push(activity);
         }
       }
       
       console.log(`合并前活动总数: ${allActivities.length}, 去重后活动总数: ${uniqueActivities.length}`);
       
       // 过滤活动，返回所有未删除的活动，并根据用户状态和店铺过滤
       const activityList = uniqueActivities
         .filter(activity => !activity.isDeleted)
         .filter(activity => {
           console.log(`检查活动 ${activity._id}:`, {
             title: activity.title,
             shopId: activity.shopId,
             shopIdType: typeof activity.shopId,
             userShopId: userShopId,
             userShopIdType: typeof userShopId,
             targetUsers: activity.targetUsers,
             userId: userId,
             userIdType: typeof userId
           });
           
          // 只显示用户绑定店铺的活动 - 修复数据类型匹配问题
          // 但是积分奖励活动（rewardType为"积分存放"）不受店铺限制
          if (activity.rewardType !== "积分存放" && userShopId && String(activity.shopId) !== String(userShopId)) {
            console.log(`活动 ${activity._id} 被过滤：店铺ID不匹配`);
            return false;
          }
           
           // 如果是每日活动，检查用户是否在目标用户列表中
           if (activity.targetUsers && activity.targetUsers.length > 0) {
             const isTargetUser = userId && activity.targetUsers.some(id => String(id) === String(userId));
             console.log(`活动 ${activity._id} 目标用户检查:`, {
               isTargetUser,
               userId,
               userIdType: typeof userId,
               targetUsers: activity.targetUsers,
               targetUsersTypes: activity.targetUsers.map(id => ({ id, type: typeof id }))
             });
             return isTargetUser;
           }
           
           console.log(`活动 ${activity._id} 通过过滤`);
           return true;
         })
         .map(activity => {
          // 解析物品ID列表和数量列表
          const goodsIds = activity.goodsList ? activity.goodsList.split(',') : [];
          const goodsSizes = activity.goodsSizeList ? activity.goodsSizeList.split(',') : [];
          
          // 构建物品信息数组
          const goodsInfo = [];
          
          for (let i = 0; i < goodsIds.length; i++) {
            const goodsId = goodsIds[i].trim();
            const size = goodsSizes[i] ? goodsSizes[i].trim() : "1";
            
            // 查找对应的物品信息（支持字符串和数字ID匹配）
            const goodsItem = goods.find(g => (g._id === parseInt(goodsId) || g._id === goodsId) && !g.isDeleted);
            
            if (goodsItem) {
              goodsInfo.push({
                size: size,
                name: goodsItem.itemName
              });
            } else {
              console.log(`活动列表中物品不存在: goodsId=${goodsId}, 类型=${typeof goodsId}`);
            }
          }
          
                     // 检查当前用户是否已领取
           const claimedUsers = activity.claimedUsers || [];
           const hasClaimed = userId ? claimedUsers.some(id => String(id) === String(userId)) : false;
          
          // 检查用户对此活动的状态
          const userState = userId ? userActivityStates.find(state => 
            String(state.userId) === String(userId) && 
            String(state.activityId) === String(activity._id)
          ) : null;
          
          // 查找店铺信息
          const shopInfo = shops.find(s => s._id === activity.shopId && !s.isDeleted);
           
           return {
             _id: activity._id,
            shopId: activity.shopId,
            shopName: shopInfo ? shopInfo.name : '未知店铺',
            tag: activity.tag || activity.title, // 每日活动使用title作为tag
             content: activity.content,
            reward: activity.reward || '每日活动奖励', // 每日活动默认奖励描述
             goodsList: goodsInfo, // 返回物品信息数组
             claimedUsers: activity.claimedUsers || [], // 已领取用户列表
             hasClaimed: hasClaimed, // 当前用户是否已领取
            userStatus: userState ? userState.status : 'normal', // 用户对此活动的状态
            createdAt: activity.createdAt,
            isDailyActivity: !!activity.targetUsers // 标记是否为每日活动
           };
        })
        // 过滤掉用户已删除或隐藏的活动
        .filter(activity => {
          if (!userId) return true; // 未登录用户看到所有活动
          return activity.userStatus !== 'deleted' && activity.userStatus !== 'hidden';
        });
      
      console.log('处理后的活动列表:', activityList);
      
      return {
        success: true,
        data: activityList,
        total: activityList.length,
        currentUserId: userId
      };
    } else {
      console.log('games集合不存在');
      return {
        success: true,
        data: [],
        total: 0,
        currentUserId: null
      };
    }
  } catch (error) {
    console.error('获取活动列表错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户信息
const getUserInfo = async (event) => {
  try {
    const { userId } = event;
    
    // 如果提供了userId，则获取指定用户信息
    if (userId) {
      const gamesResult = await db.collection("games").get();
      if (gamesResult.data.length === 0) {
        return {
          success: false,
          errMsg: '数据库初始化失败'
        };
      }
      
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const targetUser = users.find(u => String(u._id) === String(userId) && !u.isDeleted);
      
      if (!targetUser) {
        return {
          success: false,
          errMsg: '用户不存在'
        };
      }
      
      return {
        success: true,
        data: targetUser
      };
    }
    
    // 否则获取当前用户信息
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    console.log('获取用户信息，openid:', openid);
    
    // 查询games集合中的用户信息
    const gamesResult = await db.collection("games").get();
    console.log('games集合查询结果:', gamesResult.data.length, '条记录');
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const characters = gamesData.characters || [];
      const shops = gamesData.shops || [];
      
      console.log('用户数量:', users.length);
      console.log('角色数量:', characters.length);
      console.log('店铺数量:', shops.length);
      console.log('所有用户openid:', users.map(u => u._openid));
      console.log('所有角色userId:', characters.map(c => c.userId));
      
      // 根据openid查找用户
      const user = users.find(u => u._openid === openid && !u.isDeleted);
      console.log('找到用户:', user ? '是' : '否');
      
      if (user) {
        // 用户存在，查找对应的角色信息
        // 使用用户的_id来查找角色，而不是openid
        const character = characters.find(c => c.userId === user._id && !c.isDeleted);
        console.log('找到角色:', character ? '是' : '否');
        
        // 查找用户绑定的店铺信息
        let userShop = null;
        if (user.shopId) {
          userShop = shops.find(s => s._id === user.shopId && !s.isDeleted);
          console.log('找到店铺:', userShop ? userShop.name : '否');
        }
        
        if (character) {
          console.log('角色信息:', character.name, character.description);
        }
        
        // 返回用户信息、角色信息和店铺信息
        return {
          success: true,
          data: {
            user: user,
            character: character || null,
            shop: userShop || null
          },
          isNewUser: false
        };
      } else {
        // 用户不存在，返回需要创建用户的信息
        console.log('用户不存在，需要创建');
        return {
          success: true,
          data: null,
          isNewUser: true,
          openid: openid
        };
      }
    } else {
      // games集合不存在，返回需要创建用户的信息
      console.log('games集合不存在');
      return {
        success: true,
        data: null,
        isNewUser: true,
        openid: openid
      };
    }
  } catch (error) {
    console.error('获取用户信息错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 根据性别和阵营创建角色
const createCharacterByGenderAndFaction = (gender, faction) => {
  const characterConfigs = {
    // 男性角色配置 - 国王
    "1_黑桃": {
      name: "黑桃国王",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/spade_king.png",
      description: "♠ 黑桃国王，扑克牌中的最高统治者，拥有至高无上的权力"
    },
    "1_红桃": {
      name: "红桃国王",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/heart_king.png",
      description: "♥ 红桃国王，爱心与正义的化身，守护着红桃王国的和平"
    },
    "1_梅花": {
      name: "梅花国王",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/club_king.png",
      description: "♣ 梅花国王，智慧与策略的象征，统领着梅花王国的军队"
    },
    "1_方片": {
      name: "方片国王",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/diamond_king.png",
      description: "♦ 方片国王，财富与繁荣的守护者，掌管着方片王国的宝藏"
    },
    // 女性角色配置 - 皇后
    "2_黑桃": {
      name: "黑桃皇后",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/spade_queen.png",
      description: "♠ 黑桃皇后，神秘而强大的女性统治者，掌握着黑魔法的秘密"
    },
    "2_红桃": {
      name: "红桃皇后",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/heart_queen.png",
      description: "♥ 红桃皇后，美丽与善良的化身，用爱心治愈着王国的子民"
    },
    "2_梅花": {
      name: "梅花皇后",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/club_queen.png",
      description: "♣ 梅花皇后，优雅而机智的女性领袖，用智慧守护着王国"
    },
    "2_方片": {
      name: "方片皇后",
      imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/diamond_queen.png",
      description: "♦ 方片皇后，高贵而富有的女性统治者，掌管着王国的财富"
    }
  };
  
  const key = `${gender}_${faction}`;
  return characterConfigs[key] || {
    name: "神秘角色",
    imageUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
    description: "未知的神秘角色"
  };
};

// 创建用户信息
const createUser = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 获取前端传递的用户信息
    const { username, avatarUrl, gender, faction } = event;
    
    // 验证必填字段
    if (!username || !avatarUrl) {
      return {
        success: false,
        errMsg: "用户名和头像为必填项"
      };
    }
    
    // 创建用户数据
    const userData = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      _openid: openid,
      username: username,
      avatarUrl: avatarUrl,
      gender: gender || 0, // 0=未知,1=男,2=女
      faction: faction || "",
      address: "",
      level: 1,
      exp: 0,
      title: "",
      matchesPlayed: 0,
      matchesWon: 0,
      playTime: 0,
      kills: 0,
      points: 0,
      shopId: null, // 店铺ID，将在后面设置
      permission: 3, // 权限：1=超级管理员,2=管理员,3=普通用户，默认普通用户
      createdAt: new Date(),
      updatedAt: new Date(),
      isDeleted: false
    };
    
    // 根据性别和阵营创建角色
    const characterConfig = createCharacterByGenderAndFaction(gender, faction);
    const characterData = {
      _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
      userId: userData._id, // 使用用户的_id作为关联
      name: characterConfig.name,
      imageUrl: characterConfig.imageUrl,
      description: characterConfig.description,
      isDeleted: false,
      createdAt: new Date()
    };
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      // games集合存在，更新users和characters数组
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const characters = gamesData.characters || [];
      const shops = gamesData.shops || [];
      
      // 检查用户是否已存在
      const existingUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (existingUser) {
        return {
          success: false,
          errMsg: "用户已存在"
        };
      }
      
      // 检查昵称是否已存在
      const existingUsername = users.find(u => u.username === username && !u.isDeleted);
      if (existingUsername) {
        return {
          success: false,
          errMsg: "昵称已被使用，请选择其他昵称"
        };
      }
      
      // 自动绑定第一个店铺（如果存在）
      if (shops.length > 0) {
        const firstShop = shops.find(shop => !shop.isDeleted);
        if (firstShop) {
          userData.shopId = firstShop._id;
          console.log('用户自动绑定到第一个店铺:', firstShop.name, 'ID:', firstShop._id);
        }
      }
      
      // 添加新用户到users数组
      users.push(userData);
      // 添加新角色到characters数组
      characters.push(characterData);
      
      // 更新games集合
      await db.collection("games").doc(gamesData._id).update({
        data: {
          users: users,
          characters: characters
        }
      });
    } else {
      // games集合不存在，创建新的games文档
      // 先创建默认店铺数据
      const defaultShops = [
        {
          _id: 1,
          name: "默认店铺",
          description: "系统默认店铺",
          phone: "010-12345678",
          status: "active",
          isDeleted: false,
          createdAt: new Date(),
          adminUserId: null
        }
      ];
      
      // 绑定用户到第一个默认店铺
      userData.shopId = defaultShops[0]._id;
      console.log('新用户绑定到默认店铺:', defaultShops[0].name, 'ID:', defaultShops[0]._id);
      
      await db.collection("games").add({
        data: {
          users: [userData],
          characters: [characterData],
          shops: defaultShops
        }
      });
    }
    
    // 返回创建成功的用户信息和角色信息
    return {
      success: true,
      data: {
        user: userData,
        character: characterData
      }
    };
  } catch (error) {
    console.error('创建用户失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 更新用户信息
const updateUser = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 获取前端传递的用户信息
    const { username, avatarUrl, gender, faction } = event;
    
    // 验证必填字段
    if (!username) {
      return {
        success: false,
        errMsg: "用户名为必填项"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const characters = gamesData.characters || [];
    
    // 查找当前用户
    const userIndex = users.findIndex(u => u._openid === openid && !u.isDeleted);
    if (userIndex === -1) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    const currentUser = users[userIndex];
    
    // 更新用户信息
    users[userIndex] = {
      ...currentUser,
      username: username,
      avatarUrl: avatarUrl || currentUser.avatarUrl,
      gender: gender || currentUser.gender,
      faction: faction || currentUser.faction,
      updatedAt: new Date()
    };
    
    // 如果性别或阵营发生变化，更新角色信息
    if (gender !== currentUser.gender || faction !== currentUser.faction) {
      const characterConfig = createCharacterByGenderAndFaction(gender, faction);
      
      // 查找用户的角色
      const characterIndex = characters.findIndex(c => c.userId === currentUser._id && !c.isDeleted);
      
      if (characterIndex !== -1) {
        // 更新现有角色
        characters[characterIndex] = {
          ...characters[characterIndex],
          name: characterConfig.name,
          imageUrl: characterConfig.imageUrl,
          description: characterConfig.description
        };
      } else {
        // 创建新角色
        const characterData = {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: currentUser._id,
          name: characterConfig.name,
          imageUrl: characterConfig.imageUrl,
          description: characterConfig.description,
          isDeleted: false,
          createdAt: new Date()
        };
        characters.push(characterData);
      }
    }
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        characters: characters
      }
    });
    
    // 返回更新后的用户信息和角色信息
    const updatedUser = users[userIndex];
    const updatedCharacter = characters.find(c => c.userId === currentUser._id && !c.isDeleted);
    
    return {
      success: true,
      data: {
        user: updatedUser,
        character: updatedCharacter
      }
    };
    
  } catch (error) {
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 插入测试数据
const insertTestData = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const userId = Date.now() + Math.floor(Math.random() * 1000);
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    // 创建物品数据
    const goodsData = [
      {
        _id: 1001,
        itemName: "治疗药水",
        itemImage: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
        goodsType: 0, // 普通物品
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1002,
        itemName: "魔法卷轴",
        itemImage: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
        goodsType: 0, // 普通物品
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1003,
        itemName: "饮品券",
        itemImage: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/goods/优惠卷.png",
        goodsType: 1, // 饮品券
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1004,
        itemName: "门票",
        itemImage: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/goods/优惠卷.png",
        goodsType: 2, // 门票
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1005,
        itemName: "高级武器",
        itemImage: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
        goodsType: 0, // 普通物品
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1006,
        itemName: "充值兑换券",
        itemImage: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/goods/优惠卷.png",
        goodsType: 3, // 充值兑换券
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1007,
        itemName: "积分",
        itemImage: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/goods/gold.png",
        goodsType: 4, // 积分
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1008,
        itemName: "猎杀数",
        itemImage: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
        goodsType: 5, // 猎杀数（独立类型）
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      },
      {
        _id: 1009,
        itemName: "背包积分",
        itemImage: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/goods/gold.png",
        goodsType: 6, // 背包积分
        storedAt: new Date("2024-01-01"),
        usedAt: null,
        isDeleted: false
      }
    ];
    
    // 创建测试数据
    const testData = {
      users: [
        {
          _id: userId,
          _openid: openid,
          username: "游戏玩家小王",
          avatarUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
          gender: 1, // 男
          faction: "黑桃",
          address: "北京市朝阳区",
          level: 15,
          exp: 2500,
          title: "高级玩家",
          matchesPlayed: 45,
          matchesWon: 32,
          playTime: 120,
          kills: 156,
          points: 2800,
          shopId: 1, // 绑定到默认店铺
          permission: 3, // 普通用户权限
          createdAt: new Date("2024-01-01"),
          updatedAt: new Date(),
          isDeleted: false
        }
      ],
      
      characters: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: userId, // 使用用户的_id作为关联
          name: "黑桃骑士",
          imageUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
          description: "黑桃阵营的男性骑士，擅长近战攻击",
          isDeleted: false,
          createdAt: new Date("2024-01-01")
        }
      ],
      
      // 店铺表
      shops: [
        {
          _id: 1,
          name: "默认店铺",
          description: "系统默认店铺",
          phone: "010-12345678",
          createdAt: new Date("2024-01-01"),
          isDeleted: false
        },
        {
          _id: 2,
          name: "分店A",
          description: "分店A描述",
          phone: "021-87654321",
          createdAt: new Date("2024-01-01"),
          isDeleted: false
        }
      ],
      
      // 用户活动状态表
      userActivityStates: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: userId,
          activityId: Date.now() + Math.floor(Math.random() * 1000) + 1,
          status: "normal", // normal, claimed, deleted
          createdAt: new Date("2024-01-01"),
          isDeleted: false
        }
      ],
      
      goods: goodsData,
      
      dailyActivities: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          shopId: 1, // 关联到默认店铺
          tag: "每日签到",
          content: "完成每日签到获得奖励",
          reward: "积分+50",
          goodsList: "1001,1003", // 奖励治疗药水和饮品券
          goodsSizeList: "2,1", // 对应数量：治疗药水2个，饮品券1个
          claimedUsers: [], // 用户领取记录数组
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 2,
          shopId: 1, // 关联到默认店铺
          tag: "游戏对战",
          content: "参与3场游戏对战",
          reward: "经验+100",
          goodsList: "1002", // 奖励魔法卷轴
          goodsSizeList: "1", // 对应数量：魔法卷轴1个
          claimedUsers: [], // 用户领取记录数组
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 3,
          shopId: 1, // 关联到默认店铺
          tag: "击杀任务",
          content: "击杀10个敌人",
          reward: "金币+200",
          goodsList: "1005", // 奖励高级武器
          goodsSizeList: "1", // 对应数量：高级武器1个
          claimedUsers: [], // 用户领取记录数组
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 4,
          tag: "连续登录",
          content: "连续登录7天",
          reward: "积分+200",
          goodsList: "1001,1002,1004", // 奖励多种物品
          goodsSizeList: "3,2,1", // 对应数量：治疗药水3个，魔法卷轴2个，门票1个
          claimedUsers: [], // 用户领取记录数组
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 5,
          tag: "团队合作",
          content: "完成团队任务",
          reward: "经验+150",
          goodsList: "1003,1005", // 奖励饮品券和高级武器
          goodsSizeList: "2,1", // 对应数量：可乐券2个，高级武器1个
          claimedUsers: [], // 用户领取记录数组
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 6,
          tag: "背包积分活动",
          content: "完成特殊任务获得背包积分",
          reward: "背包积分+100",
          goodsList: "1009", // 奖励背包积分
          goodsSizeList: "100", // 对应数量：背包积分100个
          claimedUsers: [], // 用户领取记录数组
          createdAt: new Date(),
          isDeleted: false
        }
      ],
      
      pointsLogs: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: userId,
          changeType: "存入",
          amount: 1000,
          createdAt: new Date("2024-01-01"),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 2,
          userId: userId,
          changeType: "存入",
          amount: 500,
          createdAt: new Date("2024-01-05"),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 3,
          userId: userId,
          changeType: "取出",
          amount: 200,
          createdAt: new Date("2024-01-10"),
          isDeleted: false
        }
      ],
      
      pointsShop: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          goodsId: 1005, // 高级武器
          shopId: 1, // 关联到默认店铺
          oldPrice: 1000,
          price: 800,
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 2,
          goodsId: 1001, // 治疗药水
          shopId: 1, // 关联到默认店铺
          oldPrice: 300,
          price: 250,
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 3,
          goodsId: 1002, // 魔法卷轴
          shopId: 1, // 关联到默认店铺
          oldPrice: 500,
          price: 400,
          createdAt: new Date(),
          isDeleted: false
        }
      ],
      
      backpacks: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: userId,
          goodsId: 1001, // 治疗药水
          quantity: 5,
          storedAt: new Date("2024-01-01"),
          usedAt: null,
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 2,
          userId: userId,
          goodsId: 1002, // 魔法卷轴
          quantity: 2,
          storedAt: new Date("2024-01-03"),
          usedAt: null,
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 3,
          userId: userId,
          goodsId: 1003, // 可乐券
          quantity: 3,
          storedAt: new Date("2024-01-05"),
          usedAt: null,
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 4,
          userId: userId,
          goodsId: 1004, // 游戏门票
          quantity: 1,
          storedAt: new Date("2024-01-07"),
          usedAt: null,
          isDeleted: false
        }
      ],
      
      drinks: [
        {
          _id: 2001,
          shopId: 1, // 关联到默认店铺
          name: "可乐",
          imageUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
          price: 8,
          description: "冰镇可乐，清爽解渴",
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: 2002,
          shopId: 1, // 关联到默认店铺
          name: "奶茶",
          imageUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
          price: 15,
          description: "香浓奶茶，口感顺滑",
          createdAt: new Date(),
          isDeleted: false
        },
        {
          _id: 2003,
          shopId: 1, // 关联到默认店铺
          name: "咖啡",
          imageUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
          price: 20,
          description: "现磨咖啡，提神醒脑",
          createdAt: new Date(),
          isDeleted: false
        }
      ],
      
      bookings: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: userId,
          time: new Date("2024-01-15 14:00:00"),
          session: "下午场",
          createdAt: new Date("2024-01-10"),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 2,
          userId: userId,
          time: new Date("2024-01-16 19:00:00"),
          session: "晚场",
          createdAt: new Date("2024-01-12"),
          isDeleted: false
        }
      ],
      
      recharges: [
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 1,
          userId: userId,
          itemName: "游戏币充值",
          price: 100,
          createdAt: new Date("2024-01-01"),
          isDeleted: false
        },
        {
          _id: Date.now() + Math.floor(Math.random() * 1000) + 2,
          userId: userId,
          itemName: "会员充值",
          price: 50,
          createdAt: new Date("2024-01-08"),
          isDeleted: false
        }
      ],
      
      depositRecords: [], // 积分存放审核记录
      
      // 充值规格数据
      rechargeSpecs: [
        // 充值类型：多少钱购买多少积分
        {
          id: 1,
          type: 1, // 1: 充值类型
          name: '1000积分',
          price: 128,
          points: 1000,
          originalPrice: 150,
          sort: 1,
          status: 'active',
          createTime: new Date()
        },
        {
          id: 2,
          type: 1,
          name: '3000积分',
          price: 198,
          points: 3000,
          originalPrice: 250,
          sort: 2,
          status: 'active',
          createTime: new Date()
        },
        {
          id: 3,
          type: 1,
          name: '5000积分',
          price: 298,
          points: 5000,
          originalPrice: 400,
          sort: 3,
          status: 'active',
          createTime: new Date()
        },
        {
          id: 4,
          type: 1,
          name: '10000积分',
          price: 459,
          points: 10000,
          originalPrice: 600,
          sort: 4,
          status: 'active',
          createTime: new Date()
        },
        {
          id: 5,
          type: 1,
          name: '15000积分',
          price: 599,
          points: 15000,
          originalPrice: 800,
          sort: 5,
          status: 'active',
          createTime: new Date()
        },
        // 门票类型：支持积分或钱购买
        {
          id: 6,
          type: 2, // 2: 门票类型
          name: '门票',
          price: 58,
          points: 5000,
          originalPrice: 80,
          description: '可参加线下活动',
          sort: 6,
          status: 'active',
          createTime: new Date()
        },
        {
          id: 7,
          type: 2,
          name: 'VIP门票',
          price: 99,
          points: 8000,
          originalPrice: 120,
          description: 'VIP专享活动',
          sort: 7,
          status: 'active',
          createTime: new Date()
        },
        {
          id: 8,
          type: 2,
          name: '积分门票',
          price: 0,
          points: 3000,
          originalPrice: 0,
          description: '纯积分购买',
          sort: 8,
          status: 'active',
          createTime: new Date()
        }
      ]
    };
    
    if (gamesResult.data.length > 0) {
      // 更新现有的games文档
      await db.collection("games").doc(gamesResult.data[0]._id).update({
        data: testData
      });
    } else {
      // 创建新的games文档
      await db.collection("games").add({
        data: testData
      });
    }
    
    return {
      success: true,
      message: "测试数据插入成功（包括店铺系统、权限管理、活动状态等新功能数据）",
      data: {
        summary: {
          users: testData.users.length,
          characters: testData.characters.length,
          shops: testData.shops.length,
          goods: testData.goods.length,
          dailyActivities: testData.dailyActivities.length,
          pointsLogs: testData.pointsLogs.length,
          pointsShop: testData.pointsShop.length,
          backpacks: testData.backpacks.length,
          drinks: testData.drinks.length,
          bookings: testData.bookings.length,
          recharges: testData.recharges.length,
          rechargeSpecs: testData.rechargeSpecs.length,
          userActivityStates: testData.userActivityStates.length
        },
        details: {
          "用户信息": `${testData.users.length}个用户信息 (游戏玩家小王)`,
          "角色信息": `${testData.characters.length}个角色 (黑桃骑士)`,
          "店铺信息": `${testData.shops.length}个店铺 (默认店铺、分店A)`,
          "物品信息": `${testData.goods.length}个物品 (治疗药水、魔法卷轴、饮品券、门票、高级武器、充值兑换券、积分、猎杀数、背包积分)`,
          "每日活动": `${testData.dailyActivities.length}个每日活动 (含物品ID列表奖励)`,
          "积分记录": `${testData.pointsLogs.length}条积分记录`,
          "积分商城": `${testData.pointsShop.length}个商城商品 (关联物品)`,
          "背包物品": `${testData.backpacks.length}个背包物品 (关联物品)`,
          "饮品信息": `${testData.drinks.length}种饮品 (含价格信息)`,
          "预约记录": `${testData.bookings.length}个预约记录`,
          "充值记录": `${testData.recharges.length}条充值记录`,
          "充值规格": `${testData.rechargeSpecs.length}个充值规格 (5个积分充值 + 3个门票购买)`,
          "用户活动状态": `${testData.userActivityStates.length}个用户活动状态记录`
        }
      }
    };
    
  } catch (error) {
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 门票预约接口
const bookWithTicket = async (event) => {
  try {
    console.log('门票预约');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 获取前端传递的参数
    const { bookingTime, session } = event; // bookingTime: "2024-01-20 14:00:00", session: "下午场"
    
    console.log('预约参数:', { bookingTime, session });
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const backpacks = gamesData.backpacks || [];
    const bookings = gamesData.bookings || [];
    const goods = gamesData.goods || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    // 查找用户的门票（goodsType: 2）
    const ticketItem = backpacks.find(b => 
      b.userId === currentUser._id && 
      b.goodsId === 1004 && // 门票的ID
      !b.isDeleted && 
      b.quantity > 0
    );
    
    if (!ticketItem) {
      return {
        success: false,
        errMsg: "没有门票，请先获取门票"
      };
    }
    
    console.log('门票信息:', ticketItem);
    
    // 扣除一张门票
    const backpackIndex = backpacks.findIndex(b => b._id === ticketItem._id);
    backpacks[backpackIndex].quantity -= 1;
    
    // 如果门票数量为0，标记为删除
    if (backpacks[backpackIndex].quantity === 0) {
      backpacks[backpackIndex].isDeleted = true;
    }
    
    console.log(`扣除门票: 1张, 剩余数量: ${backpacks[backpackIndex].quantity}`);
    
    // 创建预约记录
    const newBooking = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      userId: currentUser._id,
      time: new Date(bookingTime),
      session: session,
      createdAt: new Date(),
      isDeleted: false
    };
    
    bookings.push(newBooking);
    
    console.log('预约记录已创建:', newBooking);
    
    // 添加奖励物品到背包
    const rewards = [];
    
    // 1. 添加饮品券（goodsId: 1003）
    const existingDrinkCoupon = backpacks.find(b => 
      b.userId === currentUser._id && 
      b.goodsId === 1003 && 
      !b.isDeleted
    );
    
    if (existingDrinkCoupon) {
      // 更新数量
      const couponIndex = backpacks.findIndex(b => b._id === existingDrinkCoupon._id);
      backpacks[couponIndex].quantity += 1;
      console.log(`更新饮品券数量: +1, 新数量: ${backpacks[couponIndex].quantity}`);
    } else {
      // 新增饮品券
      const newDrinkCoupon = {
        _id: Date.now() + Math.floor(Math.random() * 1000),
        userId: currentUser._id,
        goodsId: 1003, // 饮品券ID
        quantity: 1,
        source: "预约奖励",
        sourceId: newBooking._id,
        storedAt: new Date(),
        usedAt: null,
        isDeleted: false
      };
      backpacks.push(newDrinkCoupon);
      console.log('新增饮品券到背包:', newDrinkCoupon);
    }
    
    // 2. 添加充值兑换券（goodsId: 1006，goodsType: 3）
    console.log('准备添加充值兑换券，当前背包数量:', backpacks.length);
    
    const newRechargeCoupon = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      userId: currentUser._id,
      goodsId: 1006, // 充值兑换券ID
      quantity: 1,
      source: "预约奖励",
      sourceId: newBooking._id,
      storedAt: new Date(),
      usedAt: null,
      isDeleted: false
    };
    
    console.log('创建的充值兑换券对象:', newRechargeCoupon);
    backpacks.push(newRechargeCoupon);
    console.log('充值兑换券已添加到背包数组，新背包数量:', backpacks.length);
    console.log('新增充值兑换券到背包:', newRechargeCoupon);
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        backpacks: backpacks,
        bookings: bookings
      }
    });
    
    console.log('预约成功');
    console.log('更新后的背包物品数量:', backpacks.length);
    console.log('背包中的充值兑换券:', backpacks.filter(b => b.goodsId === 1006 && !b.isDeleted));
    
    return {
      success: true,
      data: {
        message: "预约成功",
        bookingId: newBooking._id,
        bookingTime: bookingTime,
        session: session,
        remainingTickets: backpacks[backpackIndex].quantity,
        rewards: {
          drinkCoupons: 1,
          rechargeCoupon: 1
        }
      }
    };
    
  } catch (error) {
    console.error('门票预约错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 检查过期兑换券（定时任务）
const checkExpiredCoupons = async (event) => {
  try {
    console.log('开始检查过期兑换券');
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      console.log('数据库不存在，跳过检查');
      return {
        success: true,
        message: "数据库不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const backpacks = gamesData.backpacks || [];
    const bookings = gamesData.bookings || [];
    
    // 获取当前时间
    const now = new Date();
    const today12pm = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 0, 0);
    
    console.log('当前时间:', now);
    console.log('今天12点:', today12pm);
    
    let expiredCount = 0;
    let updatedBackpacks = [...backpacks];
    
    // 遍历所有背包物品
    for (let i = 0; i < updatedBackpacks.length; i++) {
      const backpackItem = updatedBackpacks[i];
      
      // 只检查充值兑换券（goodsId: 1006）
      if (backpackItem.goodsId === 1006 && !backpackItem.isDeleted) {
        console.log('检查兑换券:', backpackItem);
        
        // 查找对应的预约记录
        const booking = bookings.find(b => 
          b._id === backpackItem.sourceId && 
          !b.isDeleted
        );
        
        if (booking) {
          console.log('找到对应预约:', booking);
          
          // 获取预约日期
          const bookingDate = new Date(booking.time);
          const bookingDate12pm = new Date(
            bookingDate.getFullYear(), 
            bookingDate.getMonth(), 
            bookingDate.getDate(), 
            12, 0, 0
          );
          
          console.log('预约日期12点:', bookingDate12pm);
          
          // 如果预约日期的12点已过，且兑换券未使用，则标记为过期
          if (now >= bookingDate12pm) {
            console.log('兑换券已过期，标记为删除');
            updatedBackpacks[i].isDeleted = true;
            updatedBackpacks[i].expiredAt = now;
            expiredCount++;
          }
        } else {
          console.log('未找到对应预约，可能是测试数据，跳过');
        }
      }
    }
    
    // 如果有过期兑换券，更新数据库
    if (expiredCount > 0) {
      await db.collection("games").doc(gamesData._id).update({
        data: {
          backpacks: updatedBackpacks
        }
      });
      
      console.log(`成功删除 ${expiredCount} 个过期兑换券`);
    } else {
      console.log('没有过期的兑换券');
    }
    
    return {
      success: true,
      data: {
        message: `检查完成，删除了 ${expiredCount} 个过期兑换券`,
        expiredCount: expiredCount,
        checkTime: now
      }
    };
    
  } catch (error) {
    console.error('检查过期兑换券错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 手动测试过期检查（用于测试）
const testExpiredCoupons = async (event) => {
  try {
    console.log('手动测试过期兑换券检查');
    
    // 调用检查过期兑换券函数
    const result = await checkExpiredCoupons(event);
    
    return {
      success: true,
      data: {
        message: "手动测试完成",
        result: result
      }
    };
    
  } catch (error) {
    console.error('手动测试过期兑换券错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 判断是否为审核员
const checkIsReviewer = async (event) => {
  try {
    console.log('判断是否为审核员');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 查询games集合获取用户信息
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    // 只有超级管理员和管理员可以审核
    const isReviewer = currentUser.permission === 1 || currentUser.permission === 2;
    
    console.log('当前用户信息:', {
      openid: openid,
      permission: currentUser.permission,
      username: currentUser.username
    });
    console.log('是否为审核员:', isReviewer);
    
    return {
      success: true,
      data: {
        isReviewer: isReviewer,
        currentOpenid: openid,
        userPermission: currentUser.permission,
        username: currentUser.username
      }
    };
    
  } catch (error) {
    console.error('判断审核员权限错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 积分存放接口（生成审核记录）
const depositPoints = async (event) => {
  try {
    console.log('积分存放申请');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { points, kills } = event; // 积分数和猎杀数
    
    if (!points && !kills) {
      return {
        success: false,
        errMsg: "请至少提供积分数或猎杀数"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const depositRecords = gamesData.depositRecords || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    // 创建存放记录
    const newDepositRecord = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      userId: currentUser._id,
      userOpenid: openid,
      username: currentUser.username,
      points: points || 0,
      kills: kills || 0,
      status: "pending", // pending: 待审核, approved: 已通过, rejected: 已拒绝
      reviewerOpenid: null,
      reviewTime: null,
      reviewNote: null,
      createdAt: new Date(),
      isDeleted: false
    };
    
    depositRecords.push(newDepositRecord);
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        depositRecords: depositRecords
      }
    });
    
    // 记录用户行为
    await recordUserAction({
      actionType: 'deposit',
      actionDetail: '积分存入申请',
      amount: (points || 0) + (kills || 0),
      itemName: `积分${points || 0}点，猎杀数${kills || 0}个`
    });
    
    console.log('积分存放申请已创建:', newDepositRecord);
    
    return {
      success: true,
      data: {
        message: "积分存放申请已提交，等待审核",
        depositId: newDepositRecord._id,
        points: points || 0,
        kills: kills || 0
      }
    };
    
  } catch (error) {
    console.error('积分存放申请错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 积分取出接口（直接扣除）
const withdrawPoints = async (event) => {
  try {
    console.log('积分取出');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { points } = event; // 只取积分数
    
    if (!points) {
      return {
        success: false,
        errMsg: "请提供积分数"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const pointsLogs = gamesData.pointsLogs || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const userId = currentUser._id;
    
    // 检查积分是否足够
    if (currentUser.points < points) {
      return {
        success: false,
        errMsg: `积分不足，需要${points}积分，当前只有${currentUser.points}积分`
      };
    }
    
    // 扣除积分
    const userIndex = users.findIndex(u => u._id === userId);
    if (userIndex !== -1) {
      users[userIndex].points -= points;
      users[userIndex].updatedAt = new Date();
    }
    
    // 记录积分流水
    const pointsLog = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      userId: userId,
      changeType: "取出",
      amount: -points,
      note: "积分取出",
      createdAt: new Date(),
      isDeleted: false
    };
    pointsLogs.push(pointsLog);
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        pointsLogs: pointsLogs
      }
    });
    
    // 记录用户行为
    await recordUserAction({
      actionType: 'withdraw',
      actionDetail: '积分取出',
      amount: points,
      itemName: '积分'
    });
    
    console.log('积分取出成功');
    
    return {
      success: true,
      data: {
        message: "积分取出成功",
        deductedPoints: points,
        remainingPoints: users[userIndex].points
      }
    };
    
  } catch (error) {
    console.error('积分取出错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取审核记录列表
const getDepositRecords = async (event) => {
  try {
    console.log('获取审核记录列表');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: true,
        data: []
      };
    }
    
    const gamesData = gamesResult.data[0];
    const depositRecords = gamesData.depositRecords || [];
    
    // 根据用户身份返回不同的记录
    const reviewerOpenid = "oUYLV5ajLuBplJ5b1mMh-zv3T1Hg";
    
    let filteredRecords = [];
    
    if (openid === reviewerOpenid) {
      // 审核员可以看到所有待审核的记录
      filteredRecords = depositRecords
        .filter(record => !record.isDeleted)
        .filter(record => record.status === "pending")
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    } else {
      // 普通用户只能看到自己的记录
      filteredRecords = depositRecords
        .filter(record => !record.isDeleted && record.userOpenid === openid)
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    }
    
    console.log('审核记录数量:', filteredRecords.length);
    
    return {
      success: true,
      data: filteredRecords
    };
    
  } catch (error) {
    console.error('获取审核记录错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 审核接口
const reviewDeposit = async (event) => {
  try {
    console.log('审核积分存放申请');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { depositId, action, note, approvedPoints, approvedKills, playTime } = event; // 新增参数：审核通过的积分、猎杀数、游戏时长
    
    console.log('审核参数详情:', {
      depositId,
      action,
      note,
      approvedPoints,
      approvedKills,
      playTime,
      playTimeType: typeof playTime
    });
    
    // 查询games集合获取用户信息
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    // 检查权限：只有超级管理员和管理员可以审核
    if (currentUser.permission !== 1 && currentUser.permission !== 2) {
      return {
        success: false,
        errMsg: "您没有审核权限"
      };
    }
    
    if (!depositId || !action) {
      return {
        success: false,
        errMsg: "请提供审核记录ID和审核操作"
      };
    }
    
    if (action !== "approve" && action !== "reject") {
      return {
        success: false,
        errMsg: "审核操作无效"
      };
    }
    
    const depositRecords = gamesData.depositRecords || [];
    const pointsLogs = gamesData.pointsLogs || [];
    
    // 查找审核记录
    const recordIndex = depositRecords.findIndex(r => r._id === depositId && !r.isDeleted);
    if (recordIndex === -1) {
      return {
        success: false,
        errMsg: "审核记录不存在"
      };
    }
    
    const record = depositRecords[recordIndex];
    
    // 检查记录状态
    if (record.status !== "pending") {
      return {
        success: false,
        errMsg: "该记录已被审核"
      };
    }
    
    // 更新审核记录
    depositRecords[recordIndex].status = action === "approve" ? "approved" : "rejected";
    depositRecords[recordIndex].reviewerOpenid = openid;
    depositRecords[recordIndex].reviewerName = currentUser.username;
    depositRecords[recordIndex].reviewTime = new Date();
    depositRecords[recordIndex].reviewNote = note || "";
    
    // 定义审核通过的值变量
    let finalPoints, finalKills, finalPlayTime;
    
    // 如果审核通过，记录审核通过的值
    if (action === "approve") {
      finalPoints = approvedPoints !== undefined ? parseInt(approvedPoints) : record.points;
      finalKills = approvedKills !== undefined ? parseInt(approvedKills) : record.kills;
      finalPlayTime = playTime !== undefined ? parseFloat(playTime) : 0; // 直接使用小时
      
      console.log('游戏时长记录详情:', {
        inputPlayTime: playTime,
        inputPlayTimeType: typeof playTime,
        finalPlayTime: finalPlayTime,
        note: '直接使用小时，不进行转换'
      });
      
      depositRecords[recordIndex].approvedPoints = finalPoints;
      depositRecords[recordIndex].approvedKills = finalKills;
      depositRecords[recordIndex].approvedPlayTime = finalPlayTime;
      
      console.log('审核记录更新后:', {
        approvedPoints: depositRecords[recordIndex].approvedPoints,
        approvedKills: depositRecords[recordIndex].approvedKills,
        approvedPlayTime: depositRecords[recordIndex].approvedPlayTime
      });
    }
    
    // 如果审核通过，创建活动奖励并直接添加游戏时长
    if (action === "approve") {
      const dailyActivities = gamesData.dailyActivities || [];
      
      console.log('审核通过的值:', {
        originalPoints: record.points,
        originalKills: record.kills,
        approvedPoints: depositRecords[recordIndex].approvedPoints,
        approvedKills: depositRecords[recordIndex].approvedKills,
        playTime: depositRecords[recordIndex].approvedPlayTime
      });
      
      // 直接添加游戏时长和猎杀数到用户账户
        const userIndex = users.findIndex(u => u._id === record.userId && !u.isDeleted);
        if (userIndex !== -1) {
        let hasUpdate = false;
        
        // 添加游戏时长
        if (depositRecords[recordIndex].approvedPlayTime > 0) {
          const oldPlayTime = users[userIndex].playTime || 0;
          users[userIndex].playTime = oldPlayTime + depositRecords[recordIndex].approvedPlayTime;
          hasUpdate = true;
          console.log(`游戏时长更新详情:`, {
            userId: record.userId,
            username: record.username,
            oldPlayTime: oldPlayTime,
            addedPlayTime: depositRecords[recordIndex].approvedPlayTime,
            newPlayTime: users[userIndex].playTime
          });
        }
        
        // 直接添加猎杀数到用户账户
        if (depositRecords[recordIndex].approvedKills > 0) {
          const oldKills = users[userIndex].kills || 0;
          users[userIndex].kills = oldKills + depositRecords[recordIndex].approvedKills;
          hasUpdate = true;
          console.log(`猎杀数更新详情:`, {
            userId: record.userId,
            username: record.username,
            oldKills: oldKills,
            addedKills: depositRecords[recordIndex].approvedKills,
            newKills: users[userIndex].kills
          });
        }
        
        if (hasUpdate) {
          users[userIndex].updatedAt = new Date();
        }
      } else {
        console.log(`未找到用户: userId=${record.userId}`);
      }
      
      // 创建积分奖励活动（使用审核后的值）
      if (depositRecords[recordIndex].approvedPoints > 0) {
        const pointsActivity = {
          _id: Date.now() + Math.floor(Math.random() * 1000),
          tag: `积分存放奖励 - ${record.username}`,
          content: `审核通过的积分存放奖励`,
          reward: `${depositRecords[recordIndex].approvedPoints}积分`,
          goodsList: "1007", // 积分物品ID
          goodsSizeList: depositRecords[recordIndex].approvedPoints.toString(),
          rewardType: "积分存放",
          targetUsers: [record.userId], // 指定目标用户
          claimedUsers: [], // 不直接标记为已领取，让用户手动领取
          isDeleted: false,
          createdAt: new Date(),
          depositRecordId: record._id // 关联存放记录
        };
        dailyActivities.push(pointsActivity);
        console.log('创建积分奖励活动:', pointsActivity);
      }
      
      // 猎杀数已直接添加到用户账户，不需要创建活动奖励
      
      // 更新数据库
      const updateData = {
        depositRecords: depositRecords,
        dailyActivities: dailyActivities
      };
      
      // 如果有用户数据更新（游戏时长），添加到更新数据中
      if (users.length > 0) {
        updateData.users = users;
        console.log('用户数据已更新，包含游戏时长变化');
      }
      
      await db.collection("games").doc(gamesData._id).update({
        data: updateData
      });
      
      console.log('审核通过，已创建活动奖励');
      
      return {
        success: true,
        data: {
          message: "审核通过，积分已以活动奖励形式发放（需用户领取），猎杀数和游戏时长已直接添加到用户账户",
          depositId: depositId,
          action: action,
          originalPoints: record.points,
          originalKills: record.kills,
          approvedPoints: finalPoints,
          approvedKills: finalKills,
          playTime: finalPlayTime
        }
      };
    }
    
    // 如果审核拒绝，直接更新审核记录
    if (action === "reject") {
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          depositRecords: depositRecords
        }
      });
      
      console.log('审核拒绝完成');
      
      return {
        success: true,
        data: {
          message: "审核拒绝",
          depositId: depositId,
          action: action,
          note: note || ""
        }
      };
    }
    
  } catch (error) {
    console.error('审核错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};



// 用户签到
const userSignIn = async (event) => {
  try {
    const { openid } = await getOpenId();
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const games = gamesData.data[0];
    const users = games.users || [];
    const signInRecords = games.signInRecords || [];
    
    // 查找用户
    const userIndex = users.findIndex(u => u._openid === openid);
    if (userIndex === -1) {
      return {
        success: false,
        errMsg: '用户不存在'
      };
    }
    
    const user = users[userIndex];
    
    // 检查今天是否已经签到
    const today = new Date();
    const todayStr = today.toISOString().split('T')[0]; // 格式：2024-01-15
    
    const todaySignIn = signInRecords.find(record => 
      record.userId === openid && record.date === todayStr
    );
    
    if (todaySignIn) {
      return {
        success: false,
        errMsg: '今天已经签到过了'
      };
    }
    
    // 执行签到
    const signInRecord = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      userId: openid,
      username: user.username,
      date: todayStr,
      points: 10,
      createdAt: new Date().toISOString()
    };
    
    // 更新用户积分
    users[userIndex].points += 10;
    users[userIndex].updatedAt = new Date().toISOString();
    
    // 记录积分增加行为
    await recordUserAction({
      actionType: 'points_add',
      actionDetail: '每日签到',
      amount: 10,
      itemName: '签到积分'
    });
    
    // 添加签到记录
    signInRecords.push(signInRecord);
    
    // 更新数据库
    await db.collection('games').doc(games._id).update({
      data: {
        users: users,
        signInRecords: signInRecords
      }
    });
    
    // 记录用户行为
    await recordUserAction({
      actionType: 'signin',
      actionDetail: '每日签到',
      amount: 10,
      itemName: '签到积分'
    });
    
    return {
      success: true,
      data: {
        message: '签到成功',
        points: 10,
        totalPoints: users[userIndex].points,
        signInDate: todayStr
      }
    };
    
  } catch (error) {
    console.error('签到失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户签到记录
const getUserSignInRecords = async (event) => {
  try {
    const { openid } = await getOpenId();
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const signInRecords = gamesData.data[0].signInRecords || [];
    const userSignInRecords = signInRecords.filter(record => record.userId === openid);
    
    // 按日期排序，最新的在前面
    userSignInRecords.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    return {
      success: true,
      data: userSignInRecords
    };
    
  } catch (error) {
    console.error('获取签到记录失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 创建充值订单（测试版本，不依赖微信支付）
const createRechargeOrder = async (event) => {
  try {
    const { amount, points } = event;
    const { openid } = await getOpenId();
    
    if (!amount || amount <= 0) {
      return {
        success: false,
        errMsg: '充值金额必须大于0'
      };
    }
    
    if (!points || points <= 0) {
      return {
        success: false,
        errMsg: '充值积分必须大于0'
      };
    }
    
    // 生成订单号
    const orderNo = `RECHARGE_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    // 保存充值记录到数据库
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const rechargeRecord = {
      _id: Date.now(),
      userId: openid,
      orderNo: orderNo,
      amount: amount,
      points: points,
      status: 'completed', // 测试版本直接设为完成
      createdAt: new Date(),
      updatedAt: new Date()
    };
    
    // 添加到充值记录
    const currentRecharges = gamesData.data[0].recharges || [];
    currentRecharges.push(rechargeRecord);
    
    await db.collection('games').doc(gamesData.data[0]._id).update({
      data: {
        recharges: currentRecharges
      }
    });
    
    // 记录用户行为
    await recordUserAction({
      actionType: 'recharge',
      actionDetail: `充值${amount}元获得${points}积分`,
      amount: amount,
      itemName: '积分充值',
      username: '测试用户',
      openid: openid
    });
    
    return {
      success: true,
      data: {
        orderNo: orderNo,
        amount: amount,
        points: points,
        status: 'completed'
      }
    };
    
  } catch (error) {
    console.error('创建充值订单失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取充值记录
const getRechargeRecords = async (event) => {
  try {
    const { openid } = await getOpenId();
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const recharges = gamesData.data[0].recharges || [];
    const userRecharges = recharges.filter(r => r.userId === openid);
    
    return {
      success: true,
      data: userRecharges
    };
    
  } catch (error) {
    console.error('获取充值记录失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 删除已领取的活动（用户个人删除）
const deleteClaimedActivities = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    console.log('用户个人删除已领取活动，openid:', openid);
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const activities = gamesData.dailyActivities || [];
    const users = gamesData.users || [];
    const userActivityStates = gamesData.userActivityStates || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const userId = currentUser._id;
    console.log('当前用户ID:', userId);
    
    // 找到当前用户已领取的活动
    const claimedActivities = activities.filter(activity => {
      if (activity.isDeleted) return false;
      const claimedUsers = activity.claimedUsers || [];
      return claimedUsers.some(id => String(id) === String(userId));
    });
    
    if (claimedActivities.length === 0) {
      return {
        success: true,
        data: {
          deletedCount: 0,
          message: '没有已领取的活动需要删除'
        }
      };
    }
    
    console.log('找到已领取的活动数量:', claimedActivities.length);
    
    // 更新用户活动状态，标记为已删除
    const updatedUserActivityStates = [...userActivityStates];
    
    claimedActivities.forEach(activity => {
      // 查找是否已存在该用户对此活动的状态记录
      const existingStateIndex = updatedUserActivityStates.findIndex(state => 
        String(state.userId) === String(userId) && 
        String(state.activityId) === String(activity._id)
      );
      
      if (existingStateIndex >= 0) {
        // 更新现有状态
        updatedUserActivityStates[existingStateIndex] = {
          ...updatedUserActivityStates[existingStateIndex],
          status: 'deleted',
          deletedAt: new Date()
        };
      } else {
        // 新增状态记录
        updatedUserActivityStates.push({
          _id: Date.now() + Math.floor(Math.random() * 1000),
          userId: userId,
          activityId: activity._id,
          status: 'deleted',
          deletedAt: new Date()
        });
      }
    });
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        userActivityStates: updatedUserActivityStates
      }
    });
    
    console.log('用户个人删除活动成功，删除数量:', claimedActivities.length);
    
    return {
      success: true,
      data: {
        deletedCount: claimedActivities.length,
        message: `成功删除${claimedActivities.length}个已领取的活动（仅对您隐藏）`,
        deletedActivities: claimedActivities.map(a => ({
          id: a._id,
          tag: a.tag
        }))
      }
    };
    
  } catch (error) {
    console.error('删除已领取活动失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取物品列表
const getGoodsList = async (event) => {
  try {
    console.log('获取物品列表');
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const goods = gamesData.goods || [];
      
      // 过滤掉已删除的物品
      const availableGoods = goods.filter(good => !good.isDeleted);
      
      console.log('物品列表获取成功:', availableGoods.length);
      
      return {
        success: true,
        data: availableGoods,
        message: '物品列表获取成功'
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败"
      };
    }
    
  } catch (error) {
    console.error('获取物品列表失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户列表
const getUserList = async (event) => {
  try {
    console.log('获取用户列表');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopId } = event;
    console.log('getUserList 参数:', { shopId, openid });
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以获取用户列表
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以获取用户列表"
        };
      }
      
      console.log('当前用户信息:', { 
        permission: currentUser.permission, 
        shopId: currentUser.shopId,
        username: currentUser.username 
      });
      console.log('所有用户数量:', users.length);
      console.log('传入的shopId:', shopId);
      
      // 过滤用户
      let filteredUsers = users.filter(u => !u.isDeleted);
      console.log('未删除的用户数量:', filteredUsers.length);
      
      // 如果不是超级管理员，只能看到自己店铺的用户
      if (currentUser.permission !== 1) {
        filteredUsers = filteredUsers.filter(u => 
          String(u.shopId) === String(currentUser.shopId)
        );
        console.log('普通管理员过滤后的用户数量:', filteredUsers.length, '店铺ID:', currentUser.shopId);
      } else if (shopId) {
        // 超级管理员指定店铺 - 修复数据类型匹配问题
        filteredUsers = filteredUsers.filter(u => 
          String(u.shopId) === String(shopId)
        );
        console.log('超级管理员过滤后的用户数量:', filteredUsers.length, '指定店铺ID:', shopId);
        console.log('用户shopId类型检查:', filteredUsers.map(u => ({ 
          id: u._id, 
          username: u.username,
          shopId: u.shopId, 
          shopIdType: typeof u.shopId,
          permission: u.permission
        })));
      } else {
        console.log('超级管理员未指定店铺，返回所有用户:', filteredUsers.length);
      }
      
      // 添加店铺信息
      const usersWithShop = filteredUsers.map(user => {
        const shop = shops.find(s => s._id === user.shopId && !s.isDeleted);
        return {
          ...user,
          shopName: shop ? shop.name : '未知店铺'
        };
      });
      
      console.log('获取用户列表成功:', usersWithShop.length);
      
      return {
        success: true,
        data: usersWithShop
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败"
      };
    }
    
  } catch (error) {
    console.error('获取用户列表失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 创建用户（管理员用）
const createUserByAdmin = async (event) => {
  try {
    console.log('创建用户');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { 
      username, 
      avatarUrl, 
      gender, 
      faction, 
      title, 
      rank, 
      account, 
      totalGames, 
      wins, 
      playTime, 
      kills, 
      points, 
      shopId 
    } = event;
    
    if (!username) {
      return {
        success: false,
        errMsg: "用户名不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以创建用户
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以创建用户"
        };
      }
      
      // 确定店铺ID
      const finalShopId = currentUser.permission === 1 ? shopId : currentUser.shopId;
      if (!finalShopId) {
        return {
          success: false,
          errMsg: "店铺ID不能为空"
        };
      }
      
      // 检查用户名是否已存在
      const existingUser = users.find(u => u.username === username && !u.isDeleted);
      if (existingUser) {
        return {
          success: false,
          errMsg: "用户名已存在"
        };
      }
      
      // 生成新的用户ID
      const newUserId = Date.now() + Math.floor(Math.random() * 1000);
      
      // 创建新用户
      const newUser = {
        _id: newUserId,
        username: username,
        avatarUrl: avatarUrl || '',
        gender: gender || 0,
        faction: faction || '',
        title: title || '',
        rank: rank || 0,
        account: account || '',
        totalGames: totalGames || 0,
        wins: wins || 0,
        playTime: playTime || 0, // 直接使用小时
        kills: kills || 0,
        points: points || 0,
        level: 1,
        permission: 3, // 默认为普通用户
        shopId: finalShopId,
        _openid: '', // 新用户暂时没有openid
        isDeleted: false,
        createdAt: new Date(),
        updatedAt: new Date()
      };
      
      // 添加到用户列表
      const updatedUsers = [...users, newUser];
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          users: updatedUsers
        }
      });
      
      console.log('创建用户成功:', newUser);
      
      return {
        success: true,
        data: newUser
      };
    } else {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
  } catch (error) {
    console.error('创建用户失败:', error);
    return {
      success: false,
      errMsg: "创建用户失败"
    };
  }
};

// 更新用户（管理员用）
const updateUserByAdmin = async (event) => {
  try {
    console.log('更新用户');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { 
      userId,
      username, 
      avatarUrl, 
      gender, 
      faction, 
      title, 
      rank, 
      account, 
      totalGames, 
      wins, 
      playTime, 
      kills, 
      points
    } = event;
    
    if (!userId) {
      return {
        success: false,
        errMsg: "用户ID不能为空"
      };
    }
    
    if (!username) {
      return {
        success: false,
        errMsg: "用户名不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以更新用户
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以更新用户"
        };
      }
      
      // 查找要更新的用户
      const userIndex = users.findIndex(u => u._id === userId && !u.isDeleted);
      if (userIndex === -1) {
        return {
          success: false,
          errMsg: "用户不存在"
        };
      }
      
      const targetUser = users[userIndex];
      
      // 检查权限：管理员只能更新自己店铺的用户
      if (currentUser.permission === 2 && String(targetUser.shopId) !== String(currentUser.shopId)) {
        return {
          success: false,
          errMsg: "权限不足，只能更新自己店铺的用户"
        };
      }
      
      // 检查用户名是否被其他用户使用
      const existingUser = users.find(u => u.username === username && u._id !== userId && !u.isDeleted);
      if (existingUser) {
        return {
          success: false,
          errMsg: "用户名已被其他用户使用"
        };
      }
      
      // 更新用户信息
      users[userIndex] = {
        ...targetUser,
        username: username,
        avatarUrl: avatarUrl || targetUser.avatarUrl,
        gender: gender !== undefined ? gender : targetUser.gender,
        faction: faction || targetUser.faction,
        title: title || targetUser.title,
        rank: rank !== undefined ? rank : targetUser.rank,
        account: account || targetUser.account,
        totalGames: totalGames !== undefined ? totalGames : targetUser.totalGames,
        wins: wins !== undefined ? wins : targetUser.wins,
        playTime: playTime !== undefined ? playTime : targetUser.playTime, // 直接使用小时
        kills: kills !== undefined ? kills : targetUser.kills,
        points: points !== undefined ? points : targetUser.points,
        updatedAt: new Date()
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          users: users
        }
      });
      
      console.log('更新用户成功:', users[userIndex]);
      
      return {
        success: true,
        data: users[userIndex]
      };
    } else {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
  } catch (error) {
    console.error('更新用户失败:', error);
    return {
      success: false,
      errMsg: "更新用户失败"
    };
  }
};

// 删除用户（管理员用）
const deleteUserByAdmin = async (event) => {
  try {
    console.log('删除用户');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { userId } = event;
    
    if (!userId) {
      return {
        success: false,
        errMsg: "用户ID不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以删除用户
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以删除用户"
        };
      }
      
      // 查找要删除的用户
      const userIndex = users.findIndex(u => u._id === userId && !u.isDeleted);
      if (userIndex === -1) {
        return {
          success: false,
          errMsg: "用户不存在"
        };
      }
      
      const targetUser = users[userIndex];
      
      // 检查权限：管理员只能删除自己店铺的用户
      if (currentUser.permission === 2 && String(targetUser.shopId) !== String(currentUser.shopId)) {
        return {
          success: false,
          errMsg: "权限不足，只能删除自己店铺的用户"
        };
      }
      
      // 不能删除自己
      if (targetUser._id === currentUser._id) {
        return {
          success: false,
          errMsg: "不能删除自己"
        };
      }
      
      // 软删除用户（标记为已删除）
      users[userIndex] = {
        ...targetUser,
        isDeleted: true,
        deletedAt: new Date()
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          users: users
        }
      });
      
      console.log('删除用户成功:', targetUser.username);
      
      return {
        success: true,
        data: { message: "用户删除成功" }
      };
    } else {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
  } catch (error) {
    console.error('删除用户失败:', error);
    return {
      success: false,
      errMsg: "删除用户失败"
    };
  }
};

// 获取每日活动列表
const getDailyActivities = async (event) => {
  try {
    console.log('获取每日活动列表');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { shopId } = event;
    console.log('getDailyActivities 参数:', { shopId, openid });
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const dailyActivities = gamesData.dailyActivities || [];
      const users = gamesData.users || [];
      const shops = gamesData.shops || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以获取每日活动列表
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以获取每日活动列表"
        };
      }
      
      console.log('当前用户信息:', { 
        permission: currentUser.permission, 
        shopId: currentUser.shopId,
        username: currentUser.username 
      });
      console.log('所有每日活动:', dailyActivities.length);
      console.log('传入的shopId:', shopId, '类型:', typeof shopId);
      
      // 调试：显示前几个活动的完整信息
      if (dailyActivities.length > 0) {
        console.log('前3个活动的完整信息:', dailyActivities.slice(0, 3).map(a => ({
          id: a._id,
          title: a.title,
          shopId: a.shopId,
          shopIdType: typeof a.shopId,
          isDeleted: a.isDeleted
        })));
      }
      
      // 过滤活动
      let filteredActivities = dailyActivities.filter(activity => !activity.isDeleted);
      console.log('未删除的活动数量:', filteredActivities.length);
      
      // 调试：显示所有活动的shopId信息
      console.log('所有活动的shopId信息:', filteredActivities.map(a => ({
        id: a._id,
        title: a.title,
        shopId: a.shopId,
        shopIdType: typeof a.shopId
      })));
      
      // 如果不是超级管理员，只能看到自己店铺的活动
      if (currentUser.permission !== 1) {
        filteredActivities = filteredActivities.filter(activity => 
          String(activity.shopId) === String(currentUser.shopId)
        );
        console.log('普通管理员过滤后的活动数量:', filteredActivities.length, '店铺ID:', currentUser.shopId);
      } else if (shopId) {
        // 超级管理员指定店铺 - 修复数据类型匹配问题
        filteredActivities = filteredActivities.filter(activity => 
          String(activity.shopId) === String(shopId)
        );
        console.log('超级管理员过滤后的活动数量:', filteredActivities.length, '指定店铺ID:', shopId);
        console.log('活动shopId类型检查:', filteredActivities.map(a => ({ 
          id: a._id, 
          title: a.title,
          shopId: a.shopId, 
          shopIdType: typeof a.shopId 
        })));
      } else {
        // 超级管理员未指定店铺，不返回任何活动
        console.log('超级管理员未指定店铺，返回空活动列表');
        filteredActivities = [];
      }
      
      // 添加店铺信息和统计信息
      const activitiesWithInfo = filteredActivities.map(activity => {
        const shop = shops.find(s => s._id === activity.shopId && !s.isDeleted);
        const targetUserCount = activity.targetUsers ? activity.targetUsers.length : 0;
        const claimedCount = activity.claimedUsers ? activity.claimedUsers.length : 0;
        
        return {
          ...activity,
          shopName: shop ? shop.name : '未知店铺',
          targetUserCount,
          claimedCount
        };
      });
      
      console.log('获取每日活动列表成功:', activitiesWithInfo.length);
      
      return {
        success: true,
        data: activitiesWithInfo
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败"
      };
    }
    
  } catch (error) {
    console.error('获取每日活动列表失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 添加每日活动
const addDailyActivity = async (event) => {
  try {
    console.log('添加每日活动');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { title, content, goodsList, goodsSizeList, targetUsers, shopId } = event;
    
    console.log('addDailyActivity 参数:', {
      title,
      targetUsers,
      targetUsersType: targetUsers ? targetUsers.map(id => ({ id, type: typeof id })) : [],
      shopId
    });
    
    if (!title || !content || !targetUsers || targetUsers.length === 0) {
      return {
        success: false,
        errMsg: "活动标题、内容和目标用户不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    // 临时调试：检查所有用户的ID类型
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      console.log('数据库中所有用户的ID类型:', users.map(u => ({ 
        _id: u._id, 
        idType: typeof u._id, 
        username: u.username,
        openid: u._openid 
      })));
    }
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const dailyActivities = gamesData.dailyActivities || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以添加每日活动
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以添加每日活动"
        };
      }
      
      // 确定店铺ID
      const finalShopId = currentUser.permission === 1 ? shopId : currentUser.shopId;
      if (!finalShopId) {
        return {
          success: false,
          errMsg: "店铺ID不能为空"
        };
      }
      
      // 生成新的活动ID
      const newActivityId = Date.now() + Math.floor(Math.random() * 1000);
      
      // 创建新活动
      const newActivity = {
        _id: newActivityId,
        title: title,
        content: content,
        goodsList: goodsList || '',
        goodsSizeList: goodsSizeList || '',
        shopId: finalShopId,
        targetUsers: targetUsers,
        claimedUsers: [], // 确保新活动的claimedUsers是空数组
        isDeleted: false,
        createdAt: new Date()
      };
      
      console.log('创建的新活动:', {
        _id: newActivity._id,
        title: newActivity.title,
        targetUsers: newActivity.targetUsers,
        targetUsersTypes: newActivity.targetUsers.map(id => ({ id, type: typeof id })),
        claimedUsers: newActivity.claimedUsers,
        shopId: newActivity.shopId
      });
      
      // 添加到活动列表
      const updatedActivities = [...dailyActivities, newActivity];
    
    // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
      data: {
        dailyActivities: updatedActivities
      }
    });
      
      console.log('添加每日活动成功:', newActivity);
    
    return {
      success: true,
        data: newActivity,
        message: '每日活动添加成功'
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败"
      };
    }
    
  } catch (error) {
    console.error('添加每日活动失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 更新每日活动
const updateDailyActivity = async (event) => {
  try {
    console.log('更新每日活动');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { activityId, title, content, goodsList, goodsSizeList, targetUsers } = event;
    
    if (!activityId || !title || !content || !targetUsers || targetUsers.length === 0) {
      return {
        success: false,
        errMsg: "活动ID、标题、内容和目标用户不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const dailyActivities = gamesData.dailyActivities || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以更新每日活动
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以更新每日活动"
        };
      }
      
      // 查找要更新的活动
      const activityIndex = dailyActivities.findIndex(activity => 
        String(activity._id) === String(activityId) && !activity.isDeleted
      );
      
      if (activityIndex === -1) {
        return {
          success: false,
          errMsg: "活动不存在或已被删除"
        };
      }
      
      const activity = dailyActivities[activityIndex];
      
      // 检查权限：只能更新自己店铺的活动（超级管理员除外）
      if (currentUser.permission !== 1 && activity.shopId !== currentUser.shopId) {
        return {
          success: false,
          errMsg: "权限不足，只能更新自己店铺的活动"
        };
      }
      
      // 更新活动
      const updatedActivities = [...dailyActivities];
      updatedActivities[activityIndex] = {
        ...updatedActivities[activityIndex],
        title,
        content,
        goodsList: goodsList || '',
        goodsSizeList: goodsSizeList || '',
        targetUsers,
        updatedAt: new Date()
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
      data: {
          dailyActivities: updatedActivities
        }
      });
      
      console.log('更新每日活动成功:', updatedActivities[activityIndex]);
      
      return {
        success: true,
        data: updatedActivities[activityIndex],
        message: '每日活动更新成功'
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败"
      };
    }
    
  } catch (error) {
    console.error('更新每日活动失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 删除每日活动
const deleteDailyActivity = async (event) => {
  try {
    console.log('删除每日活动');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { activityId } = event;
    
    if (!activityId) {
      return {
        success: false,
        errMsg: "活动ID不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const dailyActivities = gamesData.dailyActivities || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有管理员可以删除每日活动
      if (currentUser.permission !== 1 && currentUser.permission !== 2) {
        return {
          success: false,
          errMsg: "权限不足，只有管理员可以删除每日活动"
        };
      }
      
      // 查找要删除的活动
      const activityIndex = dailyActivities.findIndex(activity => 
        String(activity._id) === String(activityId) && !activity.isDeleted
      );
      
      if (activityIndex === -1) {
        return {
          success: false,
          errMsg: "活动不存在或已被删除"
        };
      }
      
      const activity = dailyActivities[activityIndex];
      
      // 检查权限：只能删除自己店铺的活动（超级管理员除外）
      if (currentUser.permission !== 1 && activity.shopId !== currentUser.shopId) {
        return {
          success: false,
          errMsg: "权限不足，只能删除自己店铺的活动"
        };
      }
      
      // 标记为已删除
      const updatedActivities = [...dailyActivities];
      updatedActivities[activityIndex] = {
        ...updatedActivities[activityIndex],
        isDeleted: true,
        deletedAt: new Date()
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          dailyActivities: updatedActivities
        }
      });
      
      console.log('删除每日活动成功:', activity);
      
      return {
        success: true,
        data: activity,
        message: '每日活动删除成功'
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败"
      };
    }
    
  } catch (error) {
    console.error('删除每日活动失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 使用背包积分
const useBackpackPoints = async (event) => {
  try {
    const { openid } = await getOpenId();
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const users = gamesData.data[0].users || [];
    const backpacks = gamesData.data[0].backpacks || [];
    const goods = gamesData.data[0].goods || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: '用户不存在，请先创建用户信息'
      };
    }
    
    const userId = currentUser._id;
    
    
    // 查找用户的背包积分（类型6的物品）
    console.log('使用背包积分 - 查找背包积分，用户ID:', userId, '类型:', typeof userId);
    console.log('使用背包积分 - 背包数据:', (backpacks || []).map(b => ({
      userId: b.userId,
      goodsId: b.goodsId,
      isDeleted: b.isDeleted
    })));
    
    const backpackPoints = backpacks.find(b => {
      if (String(b.userId) !== String(userId) || b.isDeleted) return false;
      
      // 查找对应的物品信息，确认是背包积分类型
      const goodsInfo = goods.find(g => (g._id === parseInt(b.goodsId) || g._id === b.goodsId) && !g.isDeleted);
      return goodsInfo && goodsInfo.goodsType === 6;
    });
    
    if (!backpackPoints) {
      return {
        success: false,
        errMsg: '背包中没有积分'
      };
    }
    
    // 查找积分物品信息
    const pointsGoods = goods.find(g => (g._id === parseInt(backpackPoints.goodsId) || g._id === backpackPoints.goodsId) && !g.isDeleted);
    if (!pointsGoods || pointsGoods.goodsType !== 6) {
      return {
        success: false,
        errMsg: '背包积分物品信息错误'
      };
    }
    
    // 使用背包积分，添加到个人账户
    const pointsToAdd = backpackPoints.quantity;
    
    // 更新用户积分
    const userIndex = users.findIndex(u => u._id === userId);
    if (userIndex !== -1) {
      users[userIndex].points += pointsToAdd;
      users[userIndex].updatedAt = new Date();
      
      // 记录积分增加行为
      await recordUserAction({
        actionType: 'points_add',
        actionDetail: '使用背包积分',
        amount: pointsToAdd,
        itemName: '背包积分'
      });
    }
    
    // 标记背包积分为已使用
    const backpackIndex = backpacks.findIndex(b => b._id === backpackPoints._id);
    if (backpackIndex !== -1) {
      backpacks[backpackIndex].isDeleted = true;
      backpacks[backpackIndex].usedAt = new Date();
    }
    
    // 添加积分流水记录
    const pointsLogs = gamesData.data[0].pointsLogs || [];
    const newPointsLog = {
      _id: Date.now(),
      userId: userId,
      changeType: '存入',
      amount: pointsToAdd,
      source: '背包积分使用',
      createdAt: new Date(),
      isDeleted: false
    };
    pointsLogs.push(newPointsLog);
    
    // 更新数据库
    await db.collection('games').doc(gamesData.data[0]._id).update({
      data: {
        users: users,
        backpacks: backpacks,
        pointsLogs: pointsLogs
      }
    });
    
    // 记录用户行为
    await recordUserAction({
      actionType: 'use_backpack_points',
      actionDetail: '使用背包积分',
      amount: pointsToAdd,
      itemName: '背包积分'
    });
    
    return {
      success: true,
      data: {
        pointsAdded: pointsToAdd,
        newPoints: users[userIndex].points,
        message: `成功使用背包积分${pointsToAdd}点，当前积分：${users[userIndex].points}`
      }
    };
    
  } catch (error) {
    console.error('使用背包积分失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取背包积分
const getBackpackPoints = async (event) => {
  try {
    const { openid } = await getOpenId();
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const users = gamesData.data[0].users || [];
    const backpacks = gamesData.data[0].backpacks || [];
    const goods = gamesData.data[0].goods || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: '用户不存在，请先创建用户信息'
      };
    }
    
    const userId = currentUser._id;
    
    // 查找用户的背包积分（类型6的物品）
    console.log('获取背包积分 - 查找背包积分，用户ID:', userId, '类型:', typeof userId);
    console.log('获取背包积分 - 背包数据:', (backpacks || []).map(b => ({
      userId: b.userId,
      goodsId: b.goodsId,
      isDeleted: b.isDeleted
    })));
    
    const backpackPoints = backpacks.find(b => {
      if (String(b.userId) !== String(userId) || b.isDeleted) return false;
      
      // 查找对应的物品信息，确认是背包积分类型
      const goodsInfo = goods.find(g => (g._id === parseInt(b.goodsId) || g._id === b.goodsId) && !g.isDeleted);
      return goodsInfo && goodsInfo.goodsType === 6;
    });
    
    if (!backpackPoints) {
      return {
        success: true,
        data: {
          hasPoints: false,
          points: 0,
          message: '背包中没有积分'
        }
      };
    }
    
    // 查找积分物品信息
    const pointsGoods = goods.find(g => (g._id === parseInt(backpackPoints.goodsId) || g._id === backpackPoints.goodsId) && !g.isDeleted);
    
    return {
      success: true,
      data: {
        hasPoints: true,
        points: backpackPoints.quantity,
        itemName: pointsGoods ? pointsGoods.itemName : '背包积分',
        storedAt: backpackPoints.storedAt,
        message: `背包中有${backpackPoints.quantity}点积分`
      }
    };
    
  } catch (error) {
    console.error('获取背包积分失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 记录用户行为并发送微信模板消息
const recordUserAction = async (event) => {
  try {
    const { openid } = await getOpenId();
    const { 
      actionType, 
      actionDetail, 
      amount, 
      itemName 
    } = event;
    
    if (!actionType || !actionDetail) {
      return {
        success: false,
        errMsg: '缺少必要参数'
      };
    }
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const users = gamesData.data[0].users || [];
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    
    if (!currentUser) {
      return {
        success: false,
        errMsg: '用户不存在'
      };
    }
    
    // 1. 记录用户行为到数据库
    const actionRecord = {
      userId: currentUser._id,
      openid: openid,
      actionType: actionType, // 'purchase', 'recharge', 'deposit', 'withdraw', 'signin', 'use_backpack_points'
      actionDetail: actionDetail,
      amount: amount || 0,
      itemName: itemName || '',
      username: currentUser.username || '用户',
      createdAt: new Date(),
      isDeleted: false
    };
    
    // 添加到games集合的userActions数组中
    const userActions = gamesData.data[0].userActions || [];
    userActions.push(actionRecord);
    
    await db.collection('games').doc(gamesData.data[0]._id).update({
      data: {
        userActions: userActions
      }
    });
    
    // 2. 发送微信模板消息
    let templateMessageStatus = '未发送';
    try {
      const templateResult = await sendWeChatTemplateMessage({
        openid: openid,
        actionType: actionType,
        actionDetail: actionDetail,
        amount: amount,
        itemName: itemName,
        username: currentUser.username
      });
      console.log('微信模板消息发送成功');
      templateMessageStatus = '发送成功';
    } catch (templateError) {
      console.error('发送微信模板消息失败:', templateError);
      templateMessageStatus = `发送失败: ${templateError.message}`;
    }
    
    return {
      success: true,
      data: actionRecord,
      message: `行为记录已保存，模板消息: ${templateMessageStatus}`
    };
  } catch (error) {
    console.error('记录用户行为失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户行为记录
const getUserActionRecords = async (event) => {
  try {
    const { openid } = await getOpenId();
    const { actionType, page = 1, pageSize = 20 } = event;
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const users = gamesData.data[0].users || [];
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    
    if (!currentUser) {
      return {
        success: false,
        errMsg: '用户不存在'
      };
    }
    
    const userActions = gamesData.data[0].userActions || [];
    
    // 筛选行为记录
    let filteredActions = userActions.filter(action => 
      String(action.userId) === String(currentUser._id) && !action.isDeleted
    );
    
    if (actionType) {
      filteredActions = filteredActions.filter(action => action.actionType === actionType);
    }
    
    // 按时间倒序排列
    filteredActions.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pagedActions = filteredActions.slice(startIndex, endIndex);
    
    return {
      success: true,
      data: pagedActions,
      total: filteredActions.length,
      page: page,
      pageSize: pageSize
    };
  } catch (error) {
    console.error('获取用户行为记录失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取微信access_token
const getAccessToken = async () => {
  try {
    console.log('开始获取access_token，AppID:', WECHAT_CONFIG.appId);
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${WECHAT_CONFIG.appId}&secret=${WECHAT_CONFIG.appSecret}`;
    
    const response = await new Promise((resolve, reject) => {
      https.get(url, (res) => {
        console.log('获取access_token响应状态码:', res.statusCode);
        let data = '';
        res.on('data', (chunk) => {
          data += chunk;
        });
        res.on('end', () => {
          console.log('获取access_token响应数据:', data);
          try {
            const parsedData = JSON.parse(data);
            resolve(parsedData);
          } catch (e) {
            reject(new Error('解析响应数据失败: ' + data));
          }
        });
      }).on('error', (error) => {
        console.error('获取access_token网络错误:', error);
        reject(error);
      });
    });
    
    console.log('获取access_token完整响应:', response);
    
    if (response.access_token) {
      console.log('获取access_token成功');
      return response.access_token;
    } else {
      console.error('获取access_token失败，响应:', response);
      throw new Error('获取access_token失败: ' + JSON.stringify(response));
    }
  } catch (error) {
    console.error('获取access_token失败:', error);
    throw error;
  }
};



// 生成服务号二维码
const generateServiceAccountQRCode = async (event) => {
  try {
    const { openid } = await getOpenId();
    const { scene, qrType = 'QR_SCENE', expireSeconds = 2592000 } = event;
    
    console.log('开始生成服务号二维码，参数:', { scene, qrType, expireSeconds });
    
    // 获取用户信息
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const users = gamesData.data[0].users || [];
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    
    if (!currentUser) {
      return {
        success: false,
        errMsg: '用户不存在'
      };
    }
    
    // 获取access_token
    console.log('开始获取access_token...');
    const accessToken = await getAccessToken();
    
    if (!accessToken) {
      return {
        success: false,
        errMsg: '获取access_token失败'
      };
    }
    
    // 检测是否为测试号，如果是则使用服务号二维码接口
    const isTestAccount = WECHAT_CONFIG.appId === 'wxdcdf0d04d9cdacd5' || WECHAT_CONFIG.appId === 'wx516b9f9fed13d03d';
    
    if (isTestAccount) {
      console.log('检测到测试号，测试号不支持公众号二维码接口');
      
      return {
        success: false,
        errMsg: '测试号不支持生成公众号二维码',
        details: '根据微信官方文档，公众号二维码接口仅支持「服务号（仅认证）」账号类型调用。测试号无法使用此功能。如需生成二维码，请使用认证的服务号或真实的小程序AppID。'
      };
    }
    
    // 真实账号使用微信API
    const codeParams = {
      scene: scene || currentUser._id // 只保留场景值
    };
    
    console.log('小程序码参数:', codeParams);
    
    // 调用微信API生成小程序码
    const url = `https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=${accessToken}`;
    console.log('调用微信API URL:', url);
    
    let response;
    try {
      response = await new Promise((resolve, reject) => {
        console.log('开始发送HTTP请求...');
      
      const req = https.request(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        timeout: 30000 // 30秒超时
      }, (res) => {
        console.log('收到微信API响应，状态码:', res.statusCode);
        
        // 检查状态码
        if (res.statusCode !== 200) {
          console.error('微信API返回错误状态码:', res.statusCode);
          let errorData = '';
          res.on('data', (chunk) => {
            errorData += chunk.toString();
          });
                      res.on('end', () => {
              console.error('错误响应数据:', errorData);
              reject(new Error(`微信API错误状态码: ${res.statusCode}, 响应: ${errorData}`));
            });
          return;
        }
        
        let data = [];
        res.on('data', (chunk) => {
          data.push(chunk);
        });
        res.on('end', () => {
          console.log('响应数据接收完成');
          const buffer = Buffer.concat(data);
          console.log('响应数据长度:', buffer.length);
          
          // 检查是否是错误响应
          try {
            const errorResponse = JSON.parse(buffer.toString());
            console.log('解析为JSON响应:', errorResponse);
            if (errorResponse.errcode) {
              console.error('微信API返回错误:', errorResponse);
              reject(new Error(`微信API错误: ${errorResponse.errcode} - ${errorResponse.errmsg}`));
              return;
            }
          } catch (e) {
            // 不是JSON，说明是图片数据
            console.log('响应是图片数据');
          }
          
          // 将图片数据转换为base64
          const base64 = buffer.toString('base64');
          console.log('base64数据长度:', base64.length);
          resolve(base64);
        });
      });
      
      req.on('error', (error) => {
        console.error('HTTP请求错误:', error);
        reject(error);
      });
      
      req.on('timeout', () => {
        console.error('HTTP请求超时');
        req.destroy();
        reject(new Error('请求超时'));
      });
      
      const requestBody = JSON.stringify(codeParams);
      console.log('发送请求体:', requestBody);
      req.write(requestBody);
      req.end();
      console.log('HTTP请求已发送');
    });
    } catch (apiError) {
      console.error('微信API调用失败:', apiError);
      throw apiError; // 重新抛出错误，不使用模拟数据
    }
    
    // 保存小程序码记录到数据库
    const qrCodes = gamesData.data[0].qrCodes || [];
    const newCode = {
      _id: Date.now() + Math.floor(Math.random() * 1000),
      userId: currentUser._id,
      scene: scene || currentUser._id,
      page: 'pages/index/index',
      codeImage: response, // base64格式的图片数据
      createTime: new Date(),
      status: 'active'
    };
    
    console.log('准备保存的小程序码记录:', {
      _id: newCode._id,
      scene: newCode.scene,
      codeImageLength: response ? response.length : 0
    });
    
    qrCodes.push(newCode);
    
    // 更新数据库
    await db.collection('games').doc(gamesData.data[0]._id).update({
      data: {
        qrCodes: qrCodes
      }
    });
    
    console.log('返回给前端的数据:', {
      success: true,
      codeImageLength: response ? response.length : 0,
      scene: scene || currentUser._id
    });
    
    return {
      success: true,
      data: {
        codeImage: response, // base64格式的图片数据
        scene: scene || currentUser._id,
        page: 'pages/index/index'
      }
    };
    
  } catch (error) {
    console.error('生成服务号二维码失败:', error);
    console.error('错误堆栈:', error.stack);
    return {
      success: false,
      errMsg: error.message,
      details: error.stack
    };
  }
};

// 获取用户的小程序码列表
// 获取充值配置列表
const getRechargeConfigs = async (event) => {
  try {
    const { type } = event; // 可选参数：recharge(充值) 或 ticket(门票)
    
    let configs = RECHARGE_CONFIGS;
    
    // 如果指定了类型，则过滤
    if (type && (type === 'recharge' || type === 'ticket')) {
      configs = RECHARGE_CONFIGS.filter(config => config.type === type);
    }
    
    return {
      success: true,
      data: configs
    };
  } catch (error) {
    console.error('获取充值配置失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取充值规格列表
const getRechargeSpecs = async (event) => {
  try {
    const { filterType } = event; // 可选参数：recharge(充值) 或 ticket(门票)
    
    const db = cloud.database();
    
    // 从games集合中获取数据
    const gamesResult = await db.collection('games').limit(1).get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库中没有找到games数据'
      };
    }
    
    let rechargeSpecs = gamesResult.data[0].rechargeSpecs || [];
    
    // 如果指定了类型，则过滤
    if (filterType) {
      if (filterType === 'recharge') {
        rechargeSpecs = rechargeSpecs.filter(spec => spec.type === 1);
      } else if (filterType === 'ticket') {
        rechargeSpecs = rechargeSpecs.filter(spec => spec.type === 2);
      }
    }
    
    // 按sort字段排序（如果存在的话）
    if (rechargeSpecs.length > 0 && rechargeSpecs[0].hasOwnProperty('sort')) {
      rechargeSpecs.sort((a, b) => (a.sort || 0) - (b.sort || 0));
    }
    
    console.log('查询到的充值规格数据:', rechargeSpecs);
    console.log('门票类型数据:', rechargeSpecs.filter(spec => spec.type === 2));
    
    return {
      success: true,
      data: rechargeSpecs
    };
  } catch (error) {
    console.error('获取充值规格失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};







const getUserQRCodes = async (event) => {
  try {
    const { openid } = await getOpenId();
    const { page = 1, pageSize = 20 } = event;
    
    const gamesData = await db.collection('games').limit(1).get();
    if (gamesData.data.length === 0) {
      return {
        success: false,
        errMsg: '数据库初始化失败'
      };
    }
    
    const users = gamesData.data[0].users || [];
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    
    if (!currentUser) {
      return {
        success: false,
        errMsg: '用户不存在'
      };
    }
    
    const qrCodes = gamesData.data[0].qrCodes || [];
    
    // 筛选当前用户的小程序码
    const userCodes = qrCodes.filter(code => 
      String(code.userId) === String(currentUser._id) && code.status === 'active'
    );
    
    // 按时间倒序排列
    userCodes.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const pagedCodes = userCodes.slice(startIndex, endIndex);
    
    return {
      success: true,
      data: pagedCodes,
      total: userCodes.length,
      page: page,
      pageSize: pageSize
    };
  } catch (error) {
    console.error('获取用户小程序码列表失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 预设的充值配置数据
const RECHARGE_CONFIGS = [
  // 充值类型：多少钱购买多少积分
  {
    id: 1,
    type: 1, // 1: 充值类型
    name: '1000积分',
    price: 128,
    points: 1000,
    originalPrice: 150,
    discount: '8.5折',
    popular: false
  },
  {
    id: 2,
    type: 1,
    name: '3000积分',
    price: 198,
    points: 3000,
    originalPrice: 250,
    discount: '7.9折',
    popular: true
  },
  {
    id: 3,
    type: 1,
    name: '5000积分',
    price: 298,
    points: 5000,
    originalPrice: 400,
    discount: '7.5折',
    popular: false
  },
  {
    id: 4,
    type: 1,
    name: '10000积分',
    price: 459,
    points: 10000,
    originalPrice: 600,
    discount: '7.7折',
    popular: false
  },
  {
    id: 5,
    type: 1,
    name: '15000积分',
    price: 599,
    points: 15000,
    originalPrice: 800,
    discount: '7.5折',
    popular: false
  },
  // 门票类型：多少钱或积分购买门票
  {
    id: 6,
    type: 2, // 2: 门票类型
    name: '门票',
    price: 58,
    points: 5000,
    originalPrice: 80,
    discount: '7.3折',
    popular: false,
    description: '可参加线下活动',
    payType: 'money' // money: 用钱购买, points: 用积分购买
  },
  {
    id: 7,
    type: 2,
    name: 'VIP门票',
    price: 99,
    points: 8000,
    originalPrice: 120,
    discount: '8.3折',
    popular: true,
    description: 'VIP专享活动',
    payType: 'money'
  },
  {
    id: 8,
    type: 2,
    name: '积分门票',
    price: 0,
    points: 3000,
    originalPrice: 0,
    discount: '',
    popular: false,
    description: '纯积分购买',
    payType: 'points'
  }
];

// 发送微信模板消息
const sendWeChatTemplateMessage = async (data) => {
  try {
    const { openid, actionType, actionDetail, amount, itemName, username } = data;
    
    // 测试号配置
    const appId = 'wxdcdf0d04d9cdacd5';
    const appSecret = '6ad94d415ba16a72470afe6f85676425';
    
    // 使用测试号中显示的 openid（需要替换为实际关注测试号的用户 openid）
    // 请从测试号页面获取正确的 openid
    const testOpenid = 'oQ4W-7UJFBY_5xgYbePN4sfOiDIs'; // 替换为你的测试号 openid
    
    // 1. 获取access_token
    const tokenResponse = await new Promise((resolve, reject) => {
      const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`;
      const request = require('request');
      request(url, (error, response, body) => {
        if (error) {
          reject(error);
        } else {
          resolve(JSON.parse(body));
        }
      });
    });
    
    if (tokenResponse.errcode) {
      throw new Error(`获取access_token失败: ${tokenResponse.errmsg}`);
    }
    
    const accessToken = tokenResponse.access_token;
    console.log('获取access_token成功:', accessToken);
    
    // 2. 发送模板消息
    const templateData = {
      touser: testOpenid, // 使用测试号的 openid
      template_id: '6K7zTNiyoD7uRNv9HtAUmZOdrgxClFfolFTlY8f50K0',
      url: '', // 点击消息跳转的链接
      data: {
        first: {
          value: `用户行为通知`,
          color: '#173177'
        },
        keyword1: {
          value: username || '用户',
          color: '#173177'
        },
        keyword2: {
          value: actionType,
          color: '#173177'
        },
        keyword3: {
          value: actionDetail,
          color: '#173177'
        },
        keyword4: {
          value: amount ? `${amount}` : '无',
          color: '#173177'
        },
        keyword5: {
          value: itemName || '无',
          color: '#173177'
        },
        remark: {
          value: `时间: ${new Date().toLocaleString('zh-CN')}`,
          color: '#173177'
        }
      }
    };
    
    const messageResponse = await new Promise((resolve, reject) => {
      const url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${accessToken}`;
      const request = require('request');
      request({
        url: url,
        method: 'POST',
        json: true,
        body: templateData
      }, (error, response, body) => {
        if (error) {
          reject(error);
        } else {
          resolve(body);
        }
      });
    });
    
    console.log('模板消息发送响应:', messageResponse);
    
    if (messageResponse.errcode && messageResponse.errcode !== 0) {
      throw new Error(`发送模板消息失败: ${messageResponse.errmsg}`);
    }
    
    return {
      success: true,
      message: '模板消息发送成功'
    };
    
  } catch (error) {
    console.error('发送微信模板消息失败:', error);
    throw error;
  }
};

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('云函数入口，event:', event);
  console.log('event.type:', event.type);
  console.log('event.action:', event.action);
  
  // 支持 type 和 action 两种参数
  const actionType = event.type || event.action;
  console.log('actionType:', actionType);
  
  switch (actionType) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection();
    case "selectRecord":
      return await selectRecord();
    case "updateRecord":
      return await updateRecord(event);
    case "insertRecord":
      return await insertRecord(event);
    case "deleteRecord":
      return await deleteRecord(event);
    case "getUserInfo":
      return await getUserInfo(event);
    case "getActivityList":
      return await getActivityList(event);
    case "getPointsShopList":
      return await getPointsShopList(event);
    case "getUserBackpack":
      return await getUserBackpack(event);
    case "purchaseShopItem":
      return await purchaseShopItem(event);
    case "clearGamesDatabase":
      return await clearGamesDatabase(event);
    case "getDrinksList":
      return await getDrinksList(event);
    case "purchaseDrink":
      return await purchaseDrink(event);
    case "addPointsShopItem":
      return await addPointsShopItem(event);
    case "updatePointsShopItem":
      return await updatePointsShopItem(event);
    case "deletePointsShopItem":
      return await deletePointsShopItem(event);
    case "getPointsShopItemsForAdmin":
      return await getPointsShopItemsForAdmin(event);
    case "addDrink":
      return await addDrink(event);
    case "updateDrink":
      return await updateDrink(event);
    case "deleteDrink":
      return await deleteDrink(event);
    case "getDrinksForAdmin":
      return await getDrinksForAdmin(event);
    case "claimActivityReward":
      return await claimActivityReward(event);
    case "createUser":
      return await createUser(event);
    case "updateUser":
      return await updateUser(event);
    case "insertTestData":
      return await insertTestData(event);
    case "bookWithTicket":
      return await bookWithTicket(event);
    case "testExpiredCoupons":
      return await testExpiredCoupons(event);
    case "checkExpiredCoupons":
      return await checkExpiredCoupons(event);
    case "checkIsReviewer":
      return await checkIsReviewer(event);
    case "depositPoints":
      return await depositPoints(event);
    case "withdrawPoints":
      return await withdrawPoints(event);
    case "getDepositRecords":
      return await getDepositRecords(event);
    case "reviewDeposit":
      return await reviewDeposit(event);
    case "createRechargeOrder":
      return await createRechargeOrder(event);
    case "getRechargeRecords":
      return await getRechargeRecords(event);
    case "userSignIn":
      return await userSignIn(event);
    case "getUserSignInRecords":
      return await getUserSignInRecords(event);
    case "deleteClaimedActivities":
      return await deleteClaimedActivities(event);
    case "getDailyActivities":
      return await getDailyActivities(event);
    case "addDailyActivity":
      return await addDailyActivity(event);
    case "updateDailyActivity":
      return await updateDailyActivity(event);
    case "deleteDailyActivity":
      return await deleteDailyActivity(event);
    case "getUserList":
      return await getUserList(event);
    case "createUser":
      return await createUserByAdmin(event);
    case "updateUser":
      return await updateUserByAdmin(event);
    case "deleteUser":
      return await deleteUserByAdmin(event);
    case "getGoodsList":
      return await getGoodsList(event);
    case "useBackpackPoints":
      return await useBackpackPoints(event);
    case "getBackpackPoints":
      return await getBackpackPoints(event);
    case "recordUserAction":
      return await recordUserAction(event);
    case "getUserActionRecords":
      return await getUserActionRecords(event);
    case "generateServiceAccountQRCode":
      return await generateServiceAccountQRCode(event);
          case "getUserQRCodes":
        return await getUserQRCodes(event);
      case "getRechargeSpecs":
        return await getRechargeSpecs(event);
      case "addRechargeSpec":
        return await addRechargeSpec(event);
      case "updateRechargeSpec":
        return await updateRechargeSpec(event);
      case "deleteRechargeSpec":
        return await deleteRechargeSpec(event);
      case "getLeaderboard":
        return await getLeaderboard(event);
      case "updateUserRankings":
        return await updateUserRankings(event);
      case "purchaseTicket":
        return await purchaseTicket(event);
      case "getUserActions":
        return await getUserActions(event);
    case "restoreDeletedActivities":
        return await restoreDeletedActivities(event);
    case "getShopList":
        return await getShopList(event);
    case "getUserShop":
        return await getUserShop(event);
    case "bindUserToShop":
        return await bindUserToShop(event);
    case "getUserPermission":
        return await getUserPermission(event);
    case "updateUserPermission":
        return await updateUserPermission(event);
    case "createShop":
        return await createShop(event);
    case "deleteShop":
        return await deleteShop(event);
    case "setShopAdmin":
        return await setShopAdmin(event);
    case "removeShopAdmin":
        return await removeShopAdmin(event);
    case "getShopAdmins":
        return await getShopAdmins(event);
    }
  };

// 购买门票
const purchaseTicket = async (event) => {
  try {
    console.log('购买门票');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    // 获取前端传递的参数
    const { usePoints, value } = event; // usePoints: true=积分购买, false=微信支付, value: 积分数或金额
    
    console.log('购买门票参数:', { usePoints, value });
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const backpacks = gamesData.backpacks || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    console.log('用户信息:', currentUser);
    
    // 根据支付方式处理购买逻辑
    if (usePoints === true) {
      // 使用积分购买
      if (currentUser.points < value) {
        return {
          success: false,
          errMsg: `积分不足，需要${value}积分，当前只有${currentUser.points}积分`
        };
      }
      
      // 扣除积分
      const userIndex = users.findIndex(u => u._id === currentUser._id);
      users[userIndex].points -= value;
      users[userIndex].updatedAt = new Date();
      
      console.log(`扣除积分: ${value}, 剩余积分: ${users[userIndex].points}`);
      
      // 记录积分减少行为
      await recordUserAction({
        actionType: 'points_subtract',
        actionDetail: '购买门票',
        amount: value,
        itemName: '门票'
      });
      
    } else {
      // 微信支付购买（暂时返回错误）
      return {
        success: false,
        errMsg: "微信支付功能暂未开放"
      };
    }
    
    // 查找用户背包中是否已有类型为2的门票物品
    const existingTicket = backpacks.find(b => 
      b.userId === currentUser._id && 
      b.goodsId === 1004 && // 门票的goodsId
      !b.isDeleted
    );
    
    if (existingTicket) {
      // 更新数量
      existingTicket.quantity += 1;
      existingTicket.updatedAt = new Date();
      console.log(`更新门票数量，新数量: ${existingTicket.quantity}`);
    } else {
      // 新增门票到背包
      const newTicket = {
        _id: Date.now() + Math.floor(Math.random() * 1000),
        userId: currentUser._id,
        goodsId: 1004, // 门票的goodsId
        quantity: 1,
        source: "购买门票",
        sourceId: Date.now(),
        storedAt: new Date(),
        usedAt: null,
        isDeleted: false
      };
      backpacks.push(newTicket);
      console.log(`新增门票到背包`);
    }
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        backpacks: backpacks
      }
    });
    
    console.log('门票购买成功');
    
    return {
      success: true,
      data: {
        message: "门票购买成功",
        ticketName: '门票',
        paymentType: usePoints ? '积分支付' : '微信支付',
        cost: usePoints ? `${value}积分` : `¥${value}`,
        remainingPoints: users.find(u => u._id === currentUser._id).points,
        remainingTickets: backpacks.find(b => 
          b.userId === currentUser._id && 
          b.goodsId === 1004 && 
          !b.isDeleted
        )?.quantity || 0
      }
    };
    
  } catch (error) {
    console.error('购买门票错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 恢复已删除的活动（用户个人恢复）
const restoreDeletedActivities = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    console.log('用户恢复已删除活动，openid:', openid);
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const userActivityStates = gamesData.userActivityStates || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const userId = currentUser._id;
    console.log('当前用户ID:', userId);
    
    // 找到当前用户已删除的活动状态
    const deletedStates = userActivityStates.filter(state => 
      String(state.userId) === String(userId) && 
      state.status === 'deleted'
    );
    
    if (deletedStates.length === 0) {
      return {
        success: true,
        data: {
          restoredCount: 0,
          message: '没有已删除的活动需要恢复'
        }
      };
    }
    
    console.log('找到已删除的活动状态数量:', deletedStates.length);
    
    // 更新用户活动状态，恢复为正常状态
    const updatedUserActivityStates = userActivityStates.map(state => {
      if (String(state.userId) === String(userId) && state.status === 'deleted') {
        return {
          ...state,
          status: 'normal',
          restoredAt: new Date()
        };
      }
      return state;
    });
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        userActivityStates: updatedUserActivityStates
      }
    });
    
    console.log('用户恢复活动成功，恢复数量:', deletedStates.length);
    
    return {
      success: true,
      data: {
        restoredCount: deletedStates.length,
        message: `成功恢复${deletedStates.length}个已删除的活动`,
        restoredActivities: deletedStates.map(state => ({
          activityId: state.activityId
        }))
      }
    };
    
  } catch (error) {
    console.error('恢复已删除活动失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取店铺列表
const getShopList = async (event) => {
  try {
    console.log('获取店铺列表');
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const shops = gamesData.shops || [];
    
    // 过滤掉已删除的店铺
    const activeShops = shops.filter(shop => !shop.isDeleted);
    
    console.log('店铺数量:', activeShops.length);
    
    return {
      success: true,
      data: activeShops,
      total: activeShops.length
    };
    
  } catch (error) {
    console.error('获取店铺列表错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户绑定的店铺
const getUserShop = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    console.log('获取用户店铺，openid:', openid);
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const shops = gamesData.shops || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const userId = currentUser._id;
    const userShopId = currentUser.shopId;
    
    if (!userShopId) {
      return {
        success: true,
        data: null,
        message: "用户未绑定店铺"
      };
    }
    
    // 查找用户绑定的店铺
    const userShop = shops.find(shop => shop._id === userShopId && !shop.isDeleted);
    
    if (!userShop) {
      return {
        success: true,
        data: null,
        message: "绑定的店铺不存在或已删除"
      };
    }
    
    return {
      success: true,
      data: userShop
    };
    
  } catch (error) {
    console.error('获取用户店铺错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 绑定用户到店铺
const bindUserToShop = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { shopId } = event;
    
    console.log('绑定用户到店铺，openid:', openid, 'shopId:', shopId);
    
    if (!shopId) {
      return {
        success: false,
        errMsg: "请提供店铺ID"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const shops = gamesData.shops || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    // 验证店铺是否存在
    const targetShop = shops.find(shop => shop._id === shopId && !shop.isDeleted);
    if (!targetShop) {
      return {
        success: false,
        errMsg: "店铺不存在或已删除"
      };
    }
    
    // 更新用户的店铺绑定
    const userIndex = users.findIndex(u => u._id === currentUser._id);
    users[userIndex] = {
      ...currentUser,
      shopId: shopId,
      updatedAt: new Date()
    };
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users
      }
    });
    
    console.log('用户绑定店铺成功');
    
    return {
      success: true,
      data: {
        message: "绑定店铺成功",
        shop: targetShop
      }
    };
    
  } catch (error) {
    console.error('绑定用户到店铺错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取用户权限
const getUserPermission = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    console.log('获取用户权限，openid:', openid);
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    const permissionLevel = currentUser.permission || 3; // 默认为普通用户
    const permissionText = getPermissionText(permissionLevel);
    
    return {
      success: true,
      data: {
        permission: permissionLevel,
        permissionText: permissionText,
        username: currentUser.username
      }
    };
    
  } catch (error) {
    console.error('获取用户权限错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 更新用户权限（仅超级管理员可操作）
const updateUserPermission = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { targetUserId, newPermission } = event;
    
    console.log('更新用户权限，openid:', openid, 'targetUserId:', targetUserId, 'newPermission:', newPermission);
    
    if (!targetUserId || !newPermission) {
      return {
        success: false,
        errMsg: "请提供目标用户ID和新权限等级"
      };
    }
    
    // 验证权限等级
    if (![1, 2, 3].includes(newPermission)) {
      return {
        success: false,
        errMsg: "权限等级无效，必须是1(超级管理员)、2(管理员)或3(普通用户)"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    
    // 查找当前用户（操作者）
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在，请先创建用户信息"
      };
    }
    
    // 检查操作者权限（只有超级管理员可以修改权限）
    if (currentUser.permission !== 1) {
      return {
        success: false,
        errMsg: "权限不足，只有超级管理员可以修改用户权限"
      };
    }
    
    // 查找目标用户
    const targetUser = users.find(u => u._id === targetUserId && !u.isDeleted);
    if (!targetUser) {
      return {
        success: false,
        errMsg: "目标用户不存在"
      };
    }
    
    // 不能修改自己的权限
    if (targetUserId === currentUser._id) {
      return {
        success: false,
        errMsg: "不能修改自己的权限"
      };
    }
    
    // 更新目标用户权限
    const userIndex = users.findIndex(u => u._id === targetUserId);
    users[userIndex] = {
      ...targetUser,
      permission: newPermission,
      updatedAt: new Date()
    };
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users
      }
    });
    
    console.log('用户权限更新成功');
    
    return {
      success: true,
      data: {
        message: "用户权限更新成功",
        targetUser: {
          userId: targetUserId,
          username: targetUser.username,
          oldPermission: targetUser.permission,
          newPermission: newPermission,
          permissionText: getPermissionText(newPermission)
        }
      }
    };
    
  } catch (error) {
    console.error('更新用户权限错误:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取权限文本描述
const getPermissionText = (permission) => {
  const permissionMap = {
    1: "超级管理员",
    2: "管理员", 
    3: "普通用户"
  };
  return permissionMap[permission] || "未知权限";
};

// 创建店铺（仅超级管理员可操作）
const createShop = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { name } = event;
    
    console.log('创建店铺，openid:', openid, 'name:', name);
    
    if (!name) {
      return {
        success: false,
        errMsg: "店铺名称为必填项"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "游戏数据不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const shops = gamesData.shops || [];
    
    // 检查当前用户权限
    const currentUser = users.find(u => u._openid === openid);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    if (currentUser.permission !== 1) {
      return {
        success: false,
        errMsg: "权限不足，只有超级管理员可以创建店铺"
      };
    }
    
    // 生成新的店铺ID
    const newShopId = shops.length > 0 ? Math.max(...shops.map(s => s._id)) + 1 : 1;
    
    // 创建新店铺
    const newShop = {
      _id: newShopId,
      name: name.trim(),
      status: "active",
      isDeleted: false,
      createdAt: new Date(),
      adminUserId: null // 初始没有管理员
    };
    
    shops.push(newShop);
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        shops: shops
      }
    });
    
    return {
      success: true,
      data: {
        shop: newShop
      }
    };
  } catch (error) {
    console.error('创建店铺失败:', error);
    return {
      success: false,
      errMsg: "创建店铺失败"
    };
  }
};

// 删除店铺（仅超级管理员可操作）
const deleteShop = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { shopId } = event;
    
    console.log('删除店铺，openid:', openid, 'shopId:', shopId);
    
    if (!shopId) {
      return {
        success: false,
        errMsg: "店铺ID不能为空"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "游戏数据不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const shops = gamesData.shops || [];
    
    // 检查当前用户权限
    const currentUser = users.find(u => u._openid === openid);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    if (currentUser.permission !== 1) {
      return {
        success: false,
        errMsg: "权限不足，只有超级管理员可以删除店铺"
      };
    }
    
    // 查找店铺
    const shopIndex = shops.findIndex(s => s._id === shopId);
    if (shopIndex === -1) {
      return {
        success: false,
        errMsg: "店铺不存在"
      };
    }
    
    // 逻辑删除店铺
    shops[shopIndex] = {
      ...shops[shopIndex],
      isDeleted: true,
      deletedAt: new Date()
    };
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        shops: shops
      }
    });
    
    return {
      success: true,
      data: {
        message: "店铺删除成功"
      }
    };
  } catch (error) {
    console.error('删除店铺失败:', error);
    return {
      success: false,
      errMsg: "删除店铺失败"
    };
  }
};

// 设置店铺管理员（仅超级管理员可操作）
const setShopAdmin = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { shopId, username } = event;
    
    console.log('设置店铺管理员，openid:', openid, 'shopId:', shopId, 'username:', username);
    
    if (!shopId || !username) {
      return {
        success: false,
        errMsg: "店铺ID和用户名不能为空"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "游戏数据不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const shops = gamesData.shops || [];
    
    // 检查当前用户权限
    const currentUser = users.find(u => u._openid === openid);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    if (currentUser.permission !== 1) {
      return {
        success: false,
        errMsg: "权限不足，只有超级管理员可以设置店铺管理员"
      };
    }
    
    // 查找店铺
    const shopIndex = shops.findIndex(s => s._id === shopId);
    if (shopIndex === -1) {
      return {
        success: false,
        errMsg: "店铺不存在"
      };
    }
    
    // 查找目标用户
    const targetUserIndex = users.findIndex(u => u.username === username.trim());
    if (targetUserIndex === -1) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    const targetUser = users[targetUserIndex];
    
    // 检查用户是否为普通用户
    if (targetUser.permission !== 3) {
      return {
        success: false,
        errMsg: "只能将普通用户设置为店铺管理员"
      };
    }
    
    // 更新用户权限和店铺绑定
    users[targetUserIndex] = {
      ...targetUser,
      permission: 2, // 设置为管理员
      shopId: shopId, // 绑定到指定店铺
      updatedAt: new Date()
    };
    
    // 注意：不再更新店铺的adminUserId，因为一个店铺可以有多个管理员
    // 管理员信息通过用户的shopId和permission字段来识别
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        shops: shops
      }
    });
    
    return {
      success: true,
      data: {
        message: "店铺管理员设置成功",
        user: {
          userId: targetUser._id,
          username: targetUser.username,
          newPermission: 2,
          shopId: shopId
        }
      }
    };
  } catch (error) {
    console.error('设置店铺管理员失败:', error);
    return {
      success: false,
      errMsg: "设置店铺管理员失败"
    };
  }
};

// 移除店铺管理员（仅超级管理员可操作）
const removeShopAdmin = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { userId } = event;
    
    console.log('移除店铺管理员，openid:', openid, 'userId:', userId);
    
    if (!userId) {
      return {
        success: false,
        errMsg: "用户ID不能为空"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "游戏数据不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const shops = gamesData.shops || [];
    
    // 检查当前用户权限
    const currentUser = users.find(u => u._openid === openid);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    if (currentUser.permission !== 1) {
      return {
        success: false,
        errMsg: "权限不足，只有超级管理员可以移除店铺管理员"
      };
    }
    
    // 查找目标用户
    const targetUserIndex = users.findIndex(u => u._id === userId);
    if (targetUserIndex === -1) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    const targetUser = users[targetUserIndex];
    
    // 检查用户是否为管理员
    if (targetUser.permission !== 2) {
      return {
        success: false,
        errMsg: "该用户不是店铺管理员"
      };
    }
    
    // 逻辑删除用户
    users[targetUserIndex] = {
      ...targetUser,
      isDeleted: true,
      deletedAt: new Date()
    };
    
    // 注意：不再需要清除店铺的adminUserId，因为一个店铺可以有多个管理员
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users,
        shops: shops
      }
    });
    
    return {
      success: true,
      data: {
        message: "店铺管理员移除成功",
        user: {
          userId: targetUser._id,
          username: targetUser.username
        }
      }
    };
  } catch (error) {
    console.error('移除店铺管理员失败:', error);
    return {
      success: false,
      errMsg: "移除店铺管理员失败"
    };
  }
};

// 获取店铺管理员列表
const getShopAdmins = async (event) => {
  try {
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    const { shopId } = event;
    
    console.log('获取店铺管理员列表，openid:', openid, 'shopId:', shopId);
    
    if (!shopId) {
      return {
        success: false,
        errMsg: "店铺ID不能为空"
      };
    }
    
    const gamesResult = await db.collection("games").get();
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "游戏数据不存在"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    
    // 检查当前用户权限
    const currentUser = users.find(u => u._openid === openid);
    if (!currentUser) {
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    if (currentUser.permission !== 1) {
      return {
        success: false,
        errMsg: "权限不足，只有超级管理员可以查看店铺管理员列表"
      };
    }
    
    // 查找该店铺的所有管理员
    const shopAdmins = users.filter(user => 
      user.shopId === shopId && 
      user.permission === 2 && 
      !user.isDeleted
    );
    
    return {
      success: true,
      data: {
        shopId: shopId,
        admins: shopAdmins.map(admin => ({
          userId: admin._id,
          username: admin.username,
          permission: admin.permission,
          shopId: admin.shopId,
          createdAt: admin.createdAt
        }))
      }
    };
  } catch (error) {
    console.error('获取店铺管理员列表失败:', error);
    return {
      success: false,
      errMsg: "获取店铺管理员列表失败"
    };
  }
};

// 添加充值规格
const addRechargeSpec = async (event) => {
  try {
    console.log('添加充值规格');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { specType, name, price, points, originalPrice, description } = event;
    
    if (!name || !price || !points) {
      return {
        success: false,
        errMsg: "规格名称、价格和积分数量不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const rechargeSpecs = gamesData.rechargeSpecs || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有超级管理员可以添加充值规格
      if (currentUser.permission !== 1) {
        return {
          success: false,
          errMsg: "权限不足，只有超级管理员可以添加充值规格"
        };
      }
      
      // 生成新的规格ID
      const newSpecId = Math.max(...rechargeSpecs.map(spec => spec.id || 0), 0) + 1;
      
      // 创建新的充值规格
      const newSpec = {
        id: newSpecId,
        type: parseInt(specType),
        name: name,
        price: parseFloat(price),
        points: parseInt(points),
        originalPrice: parseFloat(originalPrice) || parseFloat(price),
        description: description || "",
        sort: rechargeSpecs.length + 1,
        status: 'active',
        createTime: new Date()
      };
      
      // 添加新规格到数组
      rechargeSpecs.push(newSpec);
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          rechargeSpecs: rechargeSpecs
        }
      });
      
      console.log('充值规格添加成功:', newSpec);
      
      return {
        success: true,
        data: {
          message: "充值规格添加成功",
          spec: newSpec
        }
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败，请先初始化数据"
      };
    }
  } catch (error) {
    console.error('添加充值规格失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 更新充值规格
const updateRechargeSpec = async (event) => {
  try {
    console.log('更新充值规格');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { specId, specType, name, price, points, originalPrice, description } = event;
    
    if (!specId || !name || !price || !points) {
      return {
        success: false,
        errMsg: "规格ID、名称、价格和积分数量不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const rechargeSpecs = gamesData.rechargeSpecs || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有超级管理员可以更新充值规格
      if (currentUser.permission !== 1) {
        return {
          success: false,
          errMsg: "权限不足，只有超级管理员可以更新充值规格"
        };
      }
      
      // 查找要更新的规格
      const specIndex = rechargeSpecs.findIndex(spec => spec.id === parseInt(specId));
      if (specIndex === -1) {
        return {
          success: false,
          errMsg: "充值规格不存在"
        };
      }
      
      // 更新规格信息
      rechargeSpecs[specIndex] = {
        ...rechargeSpecs[specIndex],
        type: parseInt(specType),
        name: name,
        price: parseFloat(price),
        points: parseInt(points),
        originalPrice: parseFloat(originalPrice) || parseFloat(price),
        description: description || ""
      };
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          rechargeSpecs: rechargeSpecs
        }
      });
      
      console.log('充值规格更新成功:', rechargeSpecs[specIndex]);
      
      return {
        success: true,
        data: {
          message: "充值规格更新成功",
          spec: rechargeSpecs[specIndex]
        }
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败，请先初始化数据"
      };
    }
  } catch (error) {
    console.error('更新充值规格失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 删除充值规格
const deleteRechargeSpec = async (event) => {
  try {
    console.log('删除充值规格');
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    
    const { specId } = event;
    
    if (!specId) {
      return {
        success: false,
        errMsg: "规格ID不能为空"
      };
    }
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length > 0) {
      const gamesData = gamesResult.data[0];
      const users = gamesData.users || [];
      const rechargeSpecs = gamesData.rechargeSpecs || [];
      
      // 查找当前用户
      const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
      if (!currentUser) {
        return {
          success: false,
          errMsg: "用户不存在，请先创建用户信息"
        };
      }
      
      // 检查权限：只有超级管理员可以删除充值规格
      if (currentUser.permission !== 1) {
        return {
          success: false,
          errMsg: "权限不足，只有超级管理员可以删除充值规格"
        };
      }
      
      // 查找要删除的规格
      const specIndex = rechargeSpecs.findIndex(spec => spec.id === parseInt(specId));
      if (specIndex === -1) {
        return {
          success: false,
          errMsg: "充值规格不存在"
        };
      }
      
      // 删除规格（从数组中移除）
      const deletedSpec = rechargeSpecs.splice(specIndex, 1)[0];
      
      // 更新数据库
      await db.collection("games").doc(gamesData._id).update({
        data: {
          rechargeSpecs: rechargeSpecs
        }
      });
      
      console.log('充值规格删除成功:', deletedSpec);
      
      return {
        success: true,
        data: {
          message: "充值规格删除成功",
          spec: deletedSpec
        }
      };
    } else {
      return {
        success: false,
        errMsg: "数据库初始化失败，请先初始化数据"
      };
    }
  } catch (error) {
    console.error('删除充值规格失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 自动更新用户排行（每天12点执行）
const updateUserRankings = async (event) => {
  try {
    console.log('开始更新用户排行');
    
    // 查询games集合
    const gamesResult = await db.collection("games").get();
    
    if (gamesResult.data.length === 0) {
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    
    // 过滤普通用户（只对普通用户进行排行，管理员不参与）
    const normalUsers = users.filter(u => u.permission === 3 && !u.isDeleted);
    
    // 按积分数排序
    const sortedUsers = normalUsers.sort((a, b) => (b.points || 0) - (a.points || 0));
    
    // 更新每个用户的排行
    sortedUsers.forEach((user, index) => {
      const userIndex = users.findIndex(u => u._id === user._id);
      if (userIndex !== -1) {
        users[userIndex].rank = index + 1;
        users[userIndex].rankUpdatedAt = new Date();
      }
    });
    
    // 更新数据库
    await db.collection("games").doc(gamesData._id).update({
      data: {
        users: users
      }
    });
    
    console.log(`用户排行更新完成，共更新 ${sortedUsers.length} 个用户`);
    
    return {
      success: true,
      data: {
        message: `用户排行更新完成，共更新 ${sortedUsers.length} 个用户`,
        updatedCount: sortedUsers.length
      }
    };
    
  } catch (error) {
    console.error('更新用户排行失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};

// 获取排行榜数据
const getLeaderboard = async (event) => {
  try {
    console.log('获取排行榜数据');
    console.log('event参数:', event);
    
    const wxContext = cloud.getWXContext();
    const openid = wxContext.OPENID;
    console.log('用户openid:', openid);
    
    const { 
      rankingType = 'total', // total, monthly, weekly, daily, custom
      dimension = 'points', // points, kills, playTime
      page = 1, 
      pageSize = 10,
      startDate, // 自定义开始时间
      endDate    // 自定义结束时间
    } = event;
    
    console.log('解析参数:', { rankingType, dimension, page, pageSize, startDate, endDate });
    
    // 查询games集合
    console.log('开始查询games集合...');
    const gamesResult = await db.collection("games").get();
    console.log('games查询结果:', gamesResult);
    
    if (gamesResult.data.length === 0) {
      console.log('数据库中没有游戏数据');
      return {
        success: false,
        errMsg: "数据库中没有游戏数据"
      };
    }
    
    const gamesData = gamesResult.data[0];
    const users = gamesData.users || [];
    const depositRecords = gamesData.depositRecords || [];
    
    console.log('用户总数:', users.length);
    console.log('存款记录总数:', depositRecords.length);
    
    // 查找当前用户
    const currentUser = users.find(u => u._openid === openid && !u.isDeleted);
    console.log('当前用户:', currentUser);
    
    if (!currentUser) {
      console.log('用户不存在，openid:', openid);
      return {
        success: false,
        errMsg: "用户不存在"
      };
    }
    
    // 过滤普通用户（只对普通用户进行排行，管理员不参与）
    const normalUsers = users.filter(u => u.permission === 3 && !u.isDeleted);
    console.log('普通用户数量:', normalUsers.length);
    
    let ranking = [];
    let totalCount = 0;
    
    if (rankingType === 'total') {
      // 总榜：直接使用用户当前数据
      ranking = normalUsers.map(user => ({
        _id: user._id,
        username: user.username,
        avatarUrl: user.avatarUrl,
        points: user.points || 0,
        kills: user.kills || 0,
        playTime: user.playTime || 0
      }));
      
      // 根据选择的维度排序
      if (dimension === 'points') {
        ranking.sort((a, b) => b.points - a.points);
      } else if (dimension === 'kills') {
        ranking.sort((a, b) => b.kills - a.kills);
      } else if (dimension === 'playTime') {
        ranking.sort((a, b) => b.playTime - a.playTime);
      }
      
      // 添加排名
      ranking.forEach((item, index) => {
        item.rank = index + 1;
      });
      
      totalCount = ranking.length;
    } else {
      // 期间榜：根据审核通过的记录
      let startDateObj, endDateObj;
      
      if (rankingType === 'custom' && startDate && endDate) {
        // 自定义时间段
        startDateObj = new Date(startDate);
        endDateObj = new Date(endDate);
      } else {
        // 预设时间段
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        switch (rankingType) {
          case 'daily':
            startDateObj = today;
            endDateObj = new Date(today);
            endDateObj.setDate(today.getDate() + 1);
            console.log('日榜时间范围计算:', {
              now: now.toISOString(),
              today: today.toISOString(),
              startDateObj: startDateObj.toISOString(),
              endDateObj: endDateObj.toISOString()
            });
            break;
          case 'weekly':
            startDateObj = new Date(today);
            startDateObj.setDate(today.getDate() - today.getDay()); // 本周一
            endDateObj = new Date(startDateObj);
            endDateObj.setDate(startDateObj.getDate() + 7);
            break;
          case 'monthly':
            startDateObj = new Date(now.getFullYear(), now.getMonth(), 1); // 本月1号
            endDateObj = new Date(now.getFullYear(), now.getMonth() + 1, 1); // 下月1号
            break;
          default:
            startDateObj = today;
            endDateObj = new Date(today);
            endDateObj.setDate(today.getDate() + 1);
        }
      }
      
      console.log(`时间范围 (${rankingType}):`, {
        startDate: startDateObj.toISOString(),
        endDate: endDateObj.toISOString()
      });
      
      // 调试：显示所有审核记录的时间
      console.log('所有审核记录时间:', depositRecords.map(record => ({
        _id: record._id,
        userId: record.userId,
        username: record.username,
        status: record.status,
        reviewTime: record.reviewTime,
        approvedPlayTime: record.approvedPlayTime,
        isInRange: record.status === 'approved' && record.reviewTime ? 
          (new Date(record.reviewTime) >= startDateObj && new Date(record.reviewTime) < endDateObj) : false
      })));
      
      // 筛选期间记录
      const periodRecords = depositRecords.filter(record => {
        if (record.status !== 'approved' || !record.reviewTime) return false;
        const reviewTime = new Date(record.reviewTime);
        return reviewTime >= startDateObj && reviewTime < endDateObj;
      });
      
      console.log(`期间记录数量:`, periodRecords.length);
      console.log(`期间记录详情:`, periodRecords.map(record => ({
        _id: record._id,
        userId: record.userId,
        username: record.username,
        approvedPoints: record.approvedPoints,
        approvedKills: record.approvedKills,
        approvedPlayTime: record.approvedPlayTime,
        approvedPlayTimeType: typeof record.approvedPlayTime,
        reviewTime: record.reviewTime
      })));
      
      // 按用户分组统计
      const userStats = {};
      periodRecords.forEach(record => {
        const userId = record.userId;
        if (!userStats[userId]) {
          userStats[userId] = {
            points: 0,
            kills: 0,
            playTime: 0
          };
        }
        userStats[userId].points += record.approvedPoints || 0;
        userStats[userId].kills += record.approvedKills || 0;
        userStats[userId].playTime += record.approvedPlayTime || 0;
      });
      
      console.log(`用户统计结果:`, userStats);
      console.log(`用户统计详情:`, Object.keys(userStats).map(userId => ({
        userId: userId,
        points: userStats[userId].points,
        kills: userStats[userId].kills,
        playTime: userStats[userId].playTime,
        playTimeType: typeof userStats[userId].playTime
      })));
      
      // 生成排行榜
      ranking = normalUsers.map(user => {
        const stats = userStats[user._id] || { points: 0, kills: 0, playTime: 0 };
        return {
          _id: user._id,
          username: user.username,
          avatarUrl: user.avatarUrl,
          points: stats.points,
          kills: stats.kills,
          playTime: stats.playTime
        };
      }).filter(user => user.points > 0 || user.kills > 0 || user.playTime > 0);
      
      console.log(`最终排行榜数据:`, ranking.map(item => ({
        _id: item._id,
        username: item.username,
        points: item.points,
        kills: item.kills,
        playTime: item.playTime,
        playTimeType: typeof item.playTime
      })));
      
      // 根据选择的维度排序
      if (dimension === 'points') {
        ranking.sort((a, b) => b.points - a.points);
      } else if (dimension === 'kills') {
        ranking.sort((a, b) => b.kills - a.kills);
      } else if (dimension === 'playTime') {
        ranking.sort((a, b) => b.playTime - a.playTime);
      }
      
      // 添加排名
      ranking.forEach((item, index) => {
        item.rank = index + 1;
      });
      
      totalCount = ranking.length;
    }
    
    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedRanking = ranking.slice(startIndex, endIndex);
    
    const totalPages = Math.ceil(totalCount / pageSize);
    
    console.log('排行榜数据生成完成:', {
      type: rankingType,
      dimension: dimension,
      totalCount: totalCount,
      currentPage: page,
      totalPages: totalPages,
      pageSize: pageSize,
      currentPageData: paginatedRanking.length
    });
    
    return {
      success: true,
      data: {
        ranking: paginatedRanking,
        pagination: {
          currentPage: page,
          totalPages: totalPages,
          totalCount: totalCount,
          pageSize: pageSize,
          hasNext: page < totalPages,
          hasPrev: page > 1
        }
      }
    };
    
  } catch (error) {
    console.error('获取排行榜失败:', error);
    return {
      success: false,
      errMsg: error.message
    };
  }
};
